Reputation: 567
Why does the following code fail to type check:
var a = Map.empty[String, Integer]
var b: Integer = a.getOrElse("", 0)
b += 1
b = b + 1
val c: Integer = a.getOrElse("", 0) + 1
The first four lines are fine but the last line fails with “Type mismatch: expected String actual Int”. Surely this is doing the same thing as lines 2 & 4 combined?
Upvotes: 1
Views: 125
Reputation: 16324
Try using Int
instead of Integer
:
var a = Map.empty[String, Int]
var b: Int = a.getOrElse("", 0)
b += 1
b = b + 1
val c: Int = a.getOrElse("", 0) + 1
Int
and Integer
are not the same type in Scala. From this post:
Integer is just an alias for java.lang.Integer. Int is the Scala integer with the extra capabilities.
So what's happening is that when you do a.getOrElse("", 0)
, the return type is the common super type of Integer
and Int
, which is Any
. Then you try to add to an
Any`, which doesn't work!
Upvotes: 4