Javaのstaticメソッドに相当するもの
Javaのstaticメソッドは、Scalaのコンパニオンオブジェクトのメソッドに相当すると思う。
Javaでstaticメソッドを使う場合、こんな↓感じだが、
public class Main { public static void main(String[] args) throws Exception { for(int i = 0; i < 10; i++){ new User("hoge"); System.out.println(User.count); } } } class User { public static int count = 0; private String name; public User(String name){ count += 1; this.name = name; } }
Scalaだと、こんな↓感じになる。
case class User(val name: String) object User { var count = 0 def apply(name: String) = { count = count + 1 new User(name) } } for(i <- 0 to 10){ User("hoge") println(User.count) }