Pergunta

I was playing in the scala repl and found this:

scala> new java.util.HashMap[Long, Long]().get(1L)
res2: Long = 0

Why does it return that? Java hashmaps are supposed to return null for missing keys.

Foi útil?

Solução

Finding the mechanism isn't too hard.

scala> new java.util.HashMap[Long, Long]().get(1L)
res0: Long = 0

scala> :javap -prv -
Binary file res0 contains $line3.$read$$iw$$iw$
[snip]
        17: invokestatic  #30                 // Method scala/runtime/BoxesRunTime.boxToLong:(J)Ljava/lang/Long;
        20: invokevirtual #34                 // Method java/util/HashMap.get:(Ljava/lang/Object;)Ljava/lang/Object;
        23: invokestatic  #38                 // Method scala/runtime/BoxesRunTime.unboxToLong:(Ljava/lang/Object;)J

and

public static long unboxToLong(Object l) {
    return l == null ? 0 : ((java.lang.Long)l).longValue();
}

Outras dicas

In Scala, Long is an AnyVal so it cannot be null.

You should either,

  1. Use a Scala map, or
  2. Check if the key is present with containsKey(Object) like you should when you use Java.

It can't work like that in Scale, from the scala.Null documentation -

Since Null is not a subtype of value types, null is not a member of any such type. For instance, it is not possible to assign null to a variable of type scala.Int.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top