Scala exception for understanding with type annotation

I'm trying to figure out what seems like weird behavior when handling zeros and type annotations inside an understanding.

As an example:

def f(): String = null for { a <- Option("hello") b = f() } yield (a, b) 

leads to the expected:

 //> res0: Option[(String, String)] = Some((hello,null)) 

however, if I add type annotation to type b

 def f(): String = null for { a <- Option("hello") b: String = f() } yield (a, b) 

then I get an exception at runtime:

 //> scala.MatchError: (hello,null) (of class scala.Tuple2) 

Why is this happening? Is b an implicit image of type String in the first example? What will change the explicit type annotation in the second example?

(Note: examples were run in Scala 2.11.4)

+7
scala for-comprehension
source share
1 answer

null not an instance of anything:

 scala> (null: String) match { case _: String => } scala.MatchError: null ... 33 elided scala> val s: String = null s: String = null scala> s.isInstanceOf[String] res1: Boolean = false 

http://www.scala-lang.org/files/archive/spec/2.11/08-pattern-matching.html#type-patterns

The pattern type indicates a nonzero value.

One trick to show translation is a comment:

 scala> for { | a <- Option("hello") | b: String = f() | } yield (a, b) // show object $read extends scala.AnyRef { def <init>() = { super.<init>; () }; object $iw extends scala.AnyRef { def <init>() = { super.<init>; () }; import $line4.$read.$iw.$iw.f; object $iw extends scala.AnyRef { def <init>() = { super.<init>; () }; val res1 = Option("hello").map(((a) => { val b: String = f; scala.Tuple2(a, b) })).map(((x$1) => x$1: @scala.unchecked match { case scala.Tuple2((a @ _), (b @ (_: String))) => scala.Tuple2(a, b) })) } } } scala.MatchError: (hello,null) (of class scala.Tuple2) at $anonfun$2.apply(<console>:10) at $anonfun$2.apply(<console>:10) at scala.Option.map(Option.scala:145) ... 39 elided 
+7
source share

All Articles