せまい部屋

web/gameエンジニアのweblog

valとdef

ぐりとぐら

それdefでやってるけど再計算されるしvalにしといていいんじゃんみたいに突っ込まれて改めて追求

case class Sample(a: Int, b: Int) {
  val test1: Int = a * 2 + b * 3
  def test2: Int = a * 2 + b * 3
}
$ scalac Sample.scala
$ ./jad Sample.class
import scala.*;
import scala.collection.Iterator;
import scala.runtime.*;

public class Sample
    implements Product, Serializable
{
    public int a()
    {
        return a;
    }

    public int b()
    {
        return b;
    }

    public int test1()
    {
        return test1;
    }

    public int test2()
    {
        return a() * 2 + b() * 3;
    }

    // 省略
    
    public Sample(int a, int b)
    {
        this.a = a;
        this.b = b;
        super();
        scala.Product.class.$init$(this);
        test1 = a * 2 + b * 3;
    }

    private final int a;
    private final int b;
    private final int test1;
}

おっしゃるとおり