That is not a bug. That is subtype inference working correctly. If you (mistakenly) expected the return type of f to be Option[Int], say so, and you'll get a compile time error telling you about your mistake:
scala> def f(x: Int): Option[Int] = if (x % 2 == 0) { x } else { None } <console>:7: error: type mismatch; found : Int required: Option[Int] def f(x: Int): Option[Int] = if (x % 2 == 0) { x } else { None }
Re:Scala: Where it came from, Where it's going
by azth on Tuesday March 17, 2015 @02:02PM
(#9219917)
scala> def f(x: Int) = if (x % 2 == 0) { x } else { None }
f: (x: Int)Any
Which is expected. The only shared type between both branches of the `if` expression is `Any`.
Re:Scala: Where it came from, Where it's going
by zak_mc_kracken on Tuesday March 17, 2015 @02:14PM
(#9220029)
This is correct given Scala's limitation: the only common supertype between Int and Option is Any.
A language that supports union types (e.g. Ceylon) will type this expression as Int|Option[Int], which is as specific as you can get.
Re:Scala: Where it came from, Where it's going
by axiomabsolute on Tuesday March 17, 2015 @03:33PM
(#9220663)
I believe Ceylon will actually further refine Int | Option[Int] to simply Option[Int].
Option[Int] is simply an alias to the type Int | Null, so Int | Option[Int] would become Int | Int | Null after replacement, which simplifies to Int | Null since Int | Int is equivalent to just Int.
[edit: the bug is not in the scala compiler, the bug is in my code - I almost certainly did not want `f` to have type `Int => Any`. My phrasing, now edited, was misleading. ]