Methods versus function and implication in Scala

Let declare def and the equivalent function as val:

scala> def optional(x:Int):Option[String] = None optional: (x: Int)Option[String] scala> val optional2:(Int)=>Option[String] = (i:Int) => None optional2: Int => Option[String] = <function1> 

Now why doesn't it work?

 scala> List(1).flatMap(optional2) <console>:9: error: type mismatch; found : Int => Option[String] required: Int => scala.collection.GenTraversableOnce[?] List(1).flatMap(optional2) ^ 

While both of them do?

 scala> List(1).flatMap(optional) res4: List[String] = List() scala> List(1).flatMap(optional2(_)) res5: List[String] = List() 

Since Option is not a subtype of GenTraversableOnce, I think this should have something to do with implications, but I can't figure out what it is. I am using Scala 2.9.1.

+8
scala option implicits
source share
1 answer

Implicit conversion Option.option2Iterable is what List(1).flatMap(optional) and List(1).flatMap(optional2(_)) .

Your problem can be reduced to the fact that the implicit conversion will not be obtained:

 scala> val optional2:(Int)=>Option[String] = (i:Int) => None optional2: Int => Option[String] = <function1> scala> (optional2(_)): Function[Int, Iterable[String]] res0: Int => Iterable[String] = <function1> scala> (optional2): Function[Int, Iterable[String]] <console>:9: error: type mismatch; found : Int => Option[String] required: Int => Iterable[String] 

Using underscores, the compiler attempts to introduce a function and provide the necessary implicit conversion. When you simply provide optional2, the implicit conversion is not applied.

+7
source share

All Articles