scala-option

Why doesn't Option have a fold method?

…衆ロ難τιáo~ 提交于 2019-12-17 22:26:48
问题 I wonder why scala.Option doesn't have a method fold like this defined: fold(ifSome: A => B , ifNone: => B) equivalent to map(ifSome).getOrElse(ifNone) Is there no better than using map + getOrElse ? 回答1: You can do: opt foldLeft (els) ((x, y) => fun(x)) or (els /: opt) ((x,y) => fun(x)) (Both solutions will evaluate els by value, which might not be what you want. Thanks to Rex Kerr for pointing at it.) Edit: But what you really want is Scalaz’s catamorphism cata (basically a fold which not

Reading multiple variables from an object wrapped in Option[]

倾然丶 夕夏残阳落幕 提交于 2019-12-13 13:16:25
问题 I have a variable obj: Option[MyObject] and want to extract multiple variables from it - if the object is not set, default values should be used. Currently I do it like this: val var1 = obj match { case Some(o) => e.var1 case _ => "default1" } val var2 = obj match { case Some(o) => e.var2 case _ => "default2" } ... which is extremely verbose. I know I could do it like this: val var1 = if (obj.isDefined) obj.get.var1 else "default1" val var2 = if (obj.isDefined) obj.get.var2 else "default2"

make play-json read the empty string as None for a type of Option[T]

你。 提交于 2019-12-11 04:24:53
问题 I'm attempting to parse json from the GitHub API with play-json, and encountering a problem with the merge_commit_sha field on Pull Requests (incidentally, I know this field is deprecated, but don't want to discuss that in this parsing problem!). Unfortunately merge_commit_sha field comes back as the empty string in some cases: "merge_commit_sha": "" This is how the field is declared in my case class: merge_commit_sha: Option[ObjectId], I have an implicit Format[ObjectId], which does not

In Scala, is there a pre-existing library function for converting exceptions to Options?

蓝咒 提交于 2019-12-09 04:35:42
问题 This is basically to wrap java factory methods which throw exceptions if the item can't be created based on the inputs. I'm looking for something in the base library like: def exceptionToOption[A](f: => A):Option[A] ={ try{ Some(f)} catch{ case e:Exception => None} } Usage: val id:Option[UUID] = exceptionToOption(UUID.fromString("this will produce None")) I know I can write my own but I want to check I am not re-inventing the wheel. 回答1: Use scala.util.control.Exception: import scala.util

Coalescing options in Scala

情到浓时终转凉″ 提交于 2019-12-09 02:43:43
问题 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))

How can I (best) convert an Option into a Try?

夙愿已清 提交于 2019-12-09 02:14:11
问题 How can I (best) convert an Option returned by a method call into a Try (by preference, although an Either or a scalaz \/ or even a Validation might be OK) including specifying a Failure value if appropriate? For example, I have the following code, which feels kludgy, but does at least do (most of) the job: import scala.util._ case class ARef(value: String) case class BRef(value: String) case class A(ref: ARef, bRef: BRef) class MismatchException(msg: String) extends RuntimeException(msg)

Calling Java API from Scala with null argument

人走茶凉 提交于 2019-12-08 19:39:31
问题 I have some Scala code that needs to call a Java API The Java API takes arguments that may be null. My Scala, of course, uses Option . For example, let's say I have a Java object constructor Foo(Integer) where the Integer may be null . I want to call it given a Scala bar: Option[Int] . I tried this import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ val foo = Foo( bar.getOrElse(null) ) But got this compile error Error:(335, 44) type mismatch; found : Any

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

六月ゝ 毕业季﹏ 提交于 2019-12-03 18:00: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

Is there a scala identity function?

北战南征 提交于 2019-12-03 10:24:42
问题 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

scala return on first Some in list

穿精又带淫゛_ 提交于 2019-12-03 02:04:53
I have a list l:List[T1] and currently im doing the following: myfun : T1 -> Option[T2] val x: Option[T2] = l.map{ myfun(l) }.flatten.find(_=>true) The myfun function returns None or Some, flatten throws away all the None's and find returns the first element of the list if any. This seems a bit hacky to me. Im thinking that there might exist some for-comprehension or similar that will do this a bit less wasteful or more clever. For example: I dont need any subsequent answers if myfun returns any Some during the map of the list l . How about: l.toStream flatMap (myfun andThen (_.toList))