Daenyth
Daenyth

Reputation: 37461

Why does getting a missing key from java.util.HashMap[Long,Long] return 0L?

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.

Upvotes: 2

Views: 950

Answers (3)

som-snytt
som-snytt

Reputation: 39577

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();
}

Upvotes: 4

Elliott Frisch
Elliott Frisch

Reputation: 201467

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.

Upvotes: 3

My other car is a cadr
My other car is a cadr

Reputation: 1431

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

Upvotes: 3

Related Questions