scala-option

Is there a scala identity function?

风流意气都作罢 提交于 2019-12-03 01:58:45
If I have something like a List[Option[A]] and I want to convert this into a List[A] , the standard way is to use flatMap : scala> val l = List(Some("Hello"), None, Some("World")) l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World)) scala> l.flatMap( o => o) res0: List[java.lang.String] = List(Hello, World) Now o => o is just an identity function. I would have thought there'd be some way to do: l.flatMap(Identity) //return a List[String] However, I can't get this to work as you can't generify an object . I tried a few things to no avail; has anyone got something like this

Could/should an implicit conversion from T to Option[T] be added/created in Scala?

本秂侑毒 提交于 2019-12-02 21:48:25
Is this an opportunity to make things a bit more efficient (for the prorammer): I find it gets a bit tiresome having to wrap things in Some , e.g. Some(5) . What about something like this: implicit def T2OptionT( x : T) : Option[T] = if ( x == null ) None else Some(x) You would lose some type safety and possibly cause confusion. For example: val iThinkThisIsAList = 2 for (i <- iThinkThisIsAList) yield { i + 1 } I (for whatever reason) thought I had a list, and it didn't get caught by the compiler when I iterated over it because it was auto-converted to an Option[Int]. I should add that I think

Why is foreach better than get for Scala Options?

て烟熏妆下的殇ゞ 提交于 2019-12-02 17:24:55
Why using foreach , map , flatMap etc. are considered better than using get for Scala Options? If I use isEmpty I can call get safely. Daniel C. Sobral Well, it kind of comes back to "tell, don't ask". Consider these two lines: if (opt.isDefined) println(opt.get) // versus opt foreach println In the first case, you are looking inside opt and then reacting depending on what you see. In the second case you are just telling opt what you want done, and let it deal with it. The first case knows too much about Option , replicates logic internal to it, is fragile and prone to errors (it can result in

JSON to XML in Scala and dealing with Option() result

你离开我真会死。 提交于 2019-12-02 03:25:29
问题 Consider the following from the Scala interpreter: scala> JSON.parseFull("""{"name":"jack","greeting":"hello world"}""") res6: Option[Any] = Some(Map(name -> jack, greeting -> hello world)) Why is the Map returned in Some() thing? And how do I work with it? I want to put the values in an xml template: <test> <name>name goes here</name> <greeting>greeting goes here</greeting> </test> What is the Scala way of getting my map out of Some(thing) and getting those values in the xml? 回答1: You have

Coalescing options in Scala

半腔热情 提交于 2019-12-01 03:39:09
Most SQL implementations (this question has nothing to do with SQL, it is just an example) offer the function COALESCE(x1,x2,...,xn) which returns x1 if it is not NULL , x2 otherwise only if x2 is not NULL neither and so on. If all xi values are NULL then the result is NULL . I wanted to get something like SQL's COALESCE in Scala for Option values being NULL replaced by None . I'll give you some examples: > coalesce(None,Some(3),Some(4)) res0: Some(3) > coalesce(Some(1),None,Some(3),Some(4)) res1: Some(1) > coalesce(None,None) res2: None So I implemented it as: def coalesce[T](values: Option[T

Why wrapping a generic method call with Option defers ClassCastException?

若如初见. 提交于 2019-11-30 08:54:39
问题 Lets say I have an array like this*: val foo: Any = 1 : Int Option(foo.asInstanceOf[String]) which fails for obvious reason: // java.lang.ClassCastException: java.lang.Integer cannot be cast to // java.lang.String // ... 48 elided Next lets consider a following class: case class DummyRow() { val foo: Any = 1 : Int def getAs[T] = foo.asInstanceOf[T] def getAsOption[T] = Option(foo.asInstanceOf[T]) } As far as I can tell getAs should behave the same way as the previous apply followed by

Extracting field from Some in Scala

不想你离开。 提交于 2019-11-29 16:43:27
I know the fact that a Some object can be a None or one of the objects I passed. What is the ideal way of extracting a field from the Some object given the fact that it is not None? I have made a class 'At' that has 'date' as one of its fields. Since the Some class has a mixin with Product trait, the following works fine: (An object with return type Some(At)).productElement(0).asInstanceOf[At].date But is there an ideal way to do this? There are several safe ways to work with Option . If you want to retrieve the contained value, I would suggest you to use either fold , getOrElse or pattern

Why wrapping a generic method call with Option defers ClassCastException?

最后都变了- 提交于 2019-11-29 09:14:19
Lets say I have an array like this*: val foo: Any = 1 : Int Option(foo.asInstanceOf[String]) which fails for obvious reason: // java.lang.ClassCastException: java.lang.Integer cannot be cast to // java.lang.String // ... 48 elided Next lets consider a following class: case class DummyRow() { val foo: Any = 1 : Int def getAs[T] = foo.asInstanceOf[T] def getAsOption[T] = Option(foo.asInstanceOf[T]) } As far as I can tell getAs should behave the same way as the previous apply followed by asInstanceOf . Surprisingly it is not the case. When called alone it throws an exception: DummyRow().getAs

How do you stop building an Option[Collection] upon reaching the first None?

偶尔善良 提交于 2019-11-29 07:15:09
When building up a collection inside an Option , each attempt to make the next member of the collection might fail, making the collection as a whole a failure, too. Upon the first failure to make a member, I'd like to give up immediately and return None for the whole collection. What is an idiomatic way to do this in Scala? Here's one approach I've come up with: def findPartByName(name: String): Option[Part] = . . . def allParts(names: Seq[String]): Option[Seq[Part]] = names.foldLeft(Some(Seq.empty): Option[Seq[Part]]) { (result, name) => result match { case Some(parts) => findPartByName(name)

How to convert X => Option[R] to PartialFunction[X,R]

女生的网名这么多〃 提交于 2019-11-29 05:30:43
As long as we have a PartialFunction[X,R] it's very easy to convert it to a function returning Option[R] , e.g. def pfToOptf[X, R](f: PartialFunction[X,R])(x: X) = if (f.isDefinedAt(x)) Some(f(x)) else None However, what if the task is opposite: suppose I have a function f getting X as an argument and returning Option[R] as a result. And I want to make a PartialFunction[X,R] out of it. What is the best way? What I've come up with looks pretty ugly to my taste: def optfToPf[X,R](f: X => Option[R]) : PartialFunction[X,R] = { object extractor { def unapply(x: X): Option[R] = f(x) } { case