Tuesday, March 15, 2016

Scala Class and Companion Objects

In Scala you define a class like
   
     class Test(val x: Int) // with one instance variable x

You can instantiate it like
      
        new Test(1)

You can also instantiate it without new (if you think it is too much typing) by defining “companion” object of class
  
    class Test(val x: Int)

    object Test {
        def apply(x: Int) = new X(x)
    }

The object is a “companion” object of class X.  It’s contents is like “static” qualifier in Java.  Moreover, function “apply” is a special name.  You don’t need to write the name of a function if the name is “apply”.  So, you can create an instance of X now with:

    Test.apply(1)
Or
    Test(1)

No comments: