Scala. Can case class with one field be a value class?

You can have a case class that is a value class. As you can see from the example below, there is no object creation. Except of course the inevitable boxing if you would upcast to Any.

Here is a little piece of scala code

class ValueClass(val value:Int) extends AnyVal

case class ValueCaseClass(value:Int) extends AnyVal

class ValueClassTest {

  var x: ValueClass = new ValueClass(1)

  var y: ValueCaseClass = ValueCaseClass(2)

  def m1(x:ValueClass) = x.value

  def m2(x:ValueCaseClass) = x.value
}

And the bytecode, which does not contain the slightest trace of the two value classes.

Compiled from "ValueClassTest.scala"
public class ValueClassTest {
  public int x();
    Code:
       0: aload_0       
       1: getfield      #14                 // Field x:I
       4: ireturn       

  public void x_$eq(int);
    Code:
       0: aload_0       
       1: iload_1       
       2: putfield      #14                 // Field x:I
       5: return        

  public int y();
    Code:
       0: aload_0       
       1: getfield      #21                 // Field y:I
       4: ireturn       

  public void y_$eq(int);
    Code:
       0: aload_0       
       1: iload_1       
       2: putfield      #21                 // Field y:I
       5: return        

  public int m1(int);
    Code:
       0: iload_1       
       1: ireturn       

  public int m2(int);
    Code:
       0: iload_1       
       1: ireturn       

  public rklaehn.ValueClassTest();
    Code:
       0: aload_0       
       1: invokespecial #29                 // Method java/lang/Object."<init>":()V
       4: aload_0       
       5: iconst_1      
       6: putfield      #14                 // Field x:I
       9: aload_0       
      10: iconst_2      
      11: putfield      #21                 // Field y:I
      14: return        
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)