scala> def b(x:Int) = { x match { case 1 => 1; case 2 => 3.5; case k => throw new Exception("Nothing")}}
b: (x: Int)AnyVal
scala> def c(x: Int) = if (x == 1) 1 else if (x == 2) 3.5 else throw new Exception("Nothing")
c: (x: Int)Double
This is what I got from REPL. Why does scala compiler treat function b
' s return type as AnyVal
. As I think, it should be Double
.
Any pointing will be helpful.
You can declare it as def b(x:Int): Double
if you need it to be treated that way.
Without it, the compiler gets confused by the throws
clause and infers the type incorrectly. Type inference isn't perfect, sometimes you have to help the magic :)