Odd...
val h = new HashMap[Long, Int]()
def mydefault0():Int = 101
println( h.getOrElse(99, default=mydefault0 _ ) ) // Prints <function0>
def mydefault1(key:Long):Int = 102
println( h.getOrElse(98, default=mydefault1 _ ) ) // Prints <function1>
The docs say that default must be of type: => B
If I understand correctly, a no-arg function returning an Int, in this case.
Why does the example taking mydefault1 compile, as it takes an argument and so does meet the specification?
Why are functions returned, instead of functions being called to yield a default value? Apparently the typesafety has been broken because the getOrElse must return an Int, not a function. (if I misunderstood the docs and incorrectly provided a function where an Int value was required, why did the compiler let me provide a function, instead of an Int?).
edit
Clearly:
- extends HashMap and overriding default, or
- using HashMap.withDefault
also let a function by used to specify a default value. What I'd like is to be able to override the default with a function that's provided at the point of performing the lookup (i.e. the function may change during the life of the Map)
Is this possible?