See the overview documentation section "When Allocation Is Necessary".
Case classes receive special notice: "Note: You can use case classes and/or extension methods for cleaner syntax in practice."
But, as @rudiger-klaehn already said, the caveat example is supplying an AnyVal where an Any is expected:
package anything
// the caveat from the overview
trait Distance extends Any
case class Meter(val value: Double) extends AnyVal with Distance
class Foo {
def add(a: Distance, b: Distance): Distance = Meter(2.0)
}
object Test extends App {
val foo = new Foo
Console println foo.add(Meter(3.4), Meter(4.3))
}
Showing that :javap -app is fixed in the latest 2.11:
scala> :javap -app anything.Test$
public final void delayedEndpoint$anything$Test$1();
flags: ACC_PUBLIC, ACC_FINAL
Code:
stack=7, locals=1, args_size=1
0: aload_0
1: new #63 // class anything/Foo
4: dup
5: invokespecial #64 // Method anything/Foo."<init>":()V
8: putfield #60 // Field foo:Lanything/Foo;
11: getstatic #69 // Field scala/Console$.MODULE$:Lscala/Console$;
14: aload_0
15: invokevirtual #71 // Method foo:()Lanything/Foo;
18: new #73 // class anything/Meter
21: dup
22: ldc2_w #74 // double 3.4d
25: invokespecial #78 // Method anything/Meter."<init>":(D)V
28: new #73 // class anything/Meter
31: dup
32: ldc2_w #79 // double 4.3d
35: invokespecial #78 // Method anything/Meter."<init>":(D)V
38: invokevirtual #84 // Method anything/Foo.add:(Lanything/Distance;Lanything/Distance;)Lanything/Distance;
41: invokevirtual #88 // Method scala/Console$.println:(Ljava/lang/Object;)V
44: return
LocalVariableTable:
Start Length Slot Name Signature
0 45 0 this Lanything/Test$;
LineNumberTable:
line 11: 0
line 12: 11
}
There is boxing as we were warned.
(Update: actually, the PR to fix -app isn't merged yet. Stay tuned.)
AnyVal
case classes but then object allocation will be forced. Be careful with your assumptions (inspect the bytecode, profile your app, and use compiler wanring flags to make sure what you get is what you want). – Plastic