On Wednesday, July 20, 2016 at 9:18:45 PM UTC-7, BillZhang wrote:
> Thank you, but why implicit conversion did'nt work automaticly ?
getOrElse is declared as:
def getOrElse[B1 >: B](key: A, default: ⇒ B1): B1
note that the default isn't constrained to have the same type as the type of values in the map, but may be any supertype of the value type.
when you wrote:
val b = map.getOrElse(1,0L)
you didn't constrain the desired return type, but you did supply a scala.Long (not a java.lang.Long), so the compiler said OK, you must want B1 to be scala.Long then. And the supertype of scala.Long and java.lang.Long is Any, so that's the result type you got.
but when you wrote:
val b: java.lang.Long = map.getOrElse(1,0L)
you asked for B1 to be java.lang.Long. The only way for the compiler to make that typecheck was to convert 0L from scala.Long to java.lang.Long via an implicit conversion.
In general, implicit conversions are not applied unless and until typechecking fails otherwise.
Seth Tisue / Scala team / Lightbend, Inc.