Skip to content

Instantly share code, notes, and snippets.

@bbjubjub2494
Created January 13, 2019 20:23
Show Gist options
  • Save bbjubjub2494/d8de1b08f7357cb72c51f78f04b9e3fb to your computer and use it in GitHub Desktop.
Save bbjubjub2494/d8de1b08f7357cb72c51f78f04b9e3fb to your computer and use it in GitHub Desktop.
illustrating scala auto{,un}boxing
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3)
// Source File Name: Main.scala
import java.util.function.Function;
import scala.Predef$;
import scala.runtime.BoxesRunTime;
public final class Main$
{
public void main(String args[])
{
int i = BoxesRunTime.unboxToInt(Function.identity().apply(BoxesRunTime.boxToInteger(3)));
Integer integer = (Integer)Function.identity().apply(Predef$.MODULE$.int2Integer(3));
int j = BoxesRunTime.unboxToInt(Function.identity().apply(BoxesRunTime.boxToInteger(3)));
}
private Main$()
{
MODULE$ = this;
}
public static Main$ MODULE$;
static
{
new Main$();
}
}
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: packimports(3)
// Source File Name: Main.scala
public final class Main
{
public static void main(String args[])
{
Main$.MODULE$.main(args);
}
}
import java.util.function.Function.identity
object Main {
def main(args: Array[String]) {
var i1 = identity[Int]()(3)
var i2 = identity[Integer]()(3)
var i3 = identity()(3)
}
}
@bbjubjub2494
Copy link
Author

Main.scala is the source code. It is compiled using scalac, and then decompiled using jad. (jad isn't maintained anymore unfortunately.)

First of all we can see that the automatic conversion Predef.int2Integer boils down to BoxesRunTime.boxToInteger, which we can also see in the main function. In main we can see that in both cases the integer value is automatically boxed to Integer by the compiler to accommodate the Java generic method that only takes reference classes. When the static type of a return value from Java is the value class, it's unboxed, but when it's the reference class, it's not. The inferred type parameter is the value class. Note that BoxesRunTime.unboxToInt turns a null value into a 0 in the case of int.

@bbjubjub2494
Copy link
Author

bbjubjub2494 commented Jan 13, 2019

It should also be noted that when Java is asked to unbox a null Integer, it throws a NullPointerException, while scala silently converts it to the default value. (in this case 0)

See https://www.scala-lang.org/files/archive/spec/2.12/06-expressions.html#the-null-value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment