Tom
Tom

Reputation: 6342

behavior of scala.Int.unbox(null)

When I call scala.Int.unbox(null) , the result is 0

The implemention of scala.Int.unbox is:

def unbox(x: java.lang.Object): Int = x.asInstanceOf[java.lang.Integer].intValue()

But when I directly call null.asInstanceOf[java.lang.Integer].intValue(), NullPointerException is thrown, should I have missed something?

Upvotes: 0

Views: 238

Answers (1)

Shane Delmore
Shane Delmore

Reputation: 1575

Where did you find that definition? I see the Scaladoc pointing to this method which explicitly specifies 0 on null input

https://github.com/scala/scala/blob/2.13.x/src/library/scala/runtime/BoxesRunTime.java#L101

Defined as:

public static int unboxToInt(Object i) {
    return i == null ? 0 : ((java.lang.Integer)i).intValue();
} 

Upvotes: 1

Related Questions