- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Re: map Option to List
Mon, 2011-11-28, 15:43
"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
Mon, 2011-11-28, 16:07
#2
Re: map Option to List
Thank you very much.
And sorry for the waste of time. It is so obvious now...
-
Andrey
And sorry for the waste of time. It is so obvious now...
-
Andrey
Mon, 2011-11-28, 16:17
#3
Re: map Option to List
On Mon, Nov 28, 2011 at 3:47 PM, Andrey Somov <trophybase@googlemail.com> wrote:
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
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
Mon, 2011-11-28, 17:57
#4
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 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
Tue, 2011-11-29, 11:07
#5
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
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
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