This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Re: map Option to List

5 replies
Sciss
Joined: 2008-12-17,
User offline. Last seen 28 weeks 5 days ago.

"aaa" :: "bbb" :: opt.toList

On 28 Nov 2011, at 14:41, Andrey Somov wrote:

> Hi all,
> how can I append Option[String] to immutable List[String] in one line ?
>
> This solution seams to be very verbose:
>
> val opt: Option[String] = None
> val result: List[String] = "aaa" :: "bbb" :: (if (opt.isEmpty) Nil else List(opt.get))
>
> -
> Andrey

Andrey Somov
Joined: 2011-03-05,
User offline. Last seen 42 years 45 weeks ago.
map Option to List
Hi all,
how can I append Option[String] to immutable List[String] in one line ?

This solution seams to be very verbose:

val opt: Option[String] = None
val result: List[String] = "aaa" :: "bbb" :: (if (opt.isEmpty) Nil else List(opt.get))

-
Andrey
Andrey Somov
Joined: 2011-03-05,
User offline. Last seen 42 years 45 weeks ago.
Re: map Option to List
Thank you very much.

And sorry for the waste of time. It is so obvious now...

-
Andrey
Jason Zaugg
Joined: 2009-05-18,
User offline. Last seen 38 weeks 5 days ago.
Re: map Option to List
On Mon, Nov 28, 2011 at 3:47 PM, Andrey Somov <trophybase@googlemail.com> wrote:
Thank you very much.

Alternatively:
scala> val opt: Option[String] = Noneopt: Option[String] = None
scala> List("aaa", "bbb") ++ opt res0: List[java.lang.String] = List(aaa, bbb)
This relies on the implicit conversion Option.option2Iterable.
-jason 
Joshua.Suereth
Joined: 2008-09-02,
User offline. Last seen 32 weeks 6 days ago.
Re: map Option to List
I'd recommend using the ++ operation, since it's defined for all collections.  :: is really just for List (and List isn't as good a general purpose data structure as Vector, for common usages).

On Mon, Nov 28, 2011 at 10:14 AM, Jason Zaugg <jzaugg@gmail.com> wrote:
On Mon, Nov 28, 2011 at 3:47 PM, Andrey Somov <trophybase@googlemail.com> wrote:
Thank you very much.

Alternatively:
scala> val opt: Option[String] = Noneopt: Option[String] = None
scala> List("aaa", "bbb") ++ opt res0: List[java.lang.String] = List(aaa, bbb)
This relies on the implicit conversion Option.option2Iterable.
-jason 

Andrey Somov
Joined: 2011-03-05,
User offline. Last seen 42 years 45 weeks ago.
Re: map Option to List
Thank you for the proposal.
I think I will choose the Option.toList() way.
This solution is very readable and it does not require a lot of knowledge about possible implicit conversions.

-
Andrey

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland