stella stella - 3 months ago 12
Scala Question

Extending class in a singleton object

I wrote this example and was pretty wondered:

class TestMatch(val i: Int)

object TestMatch extends TestMatch(10){ // <-- Here
def apply(i: Int) = new TestMatch(i)
def unapply(tm : TestMatch): Option[Int] = Some(tm.i)
}


What's going on here? We extend
TestMatch(10)
. How can we extend an instance f test match created with
i = 10
? It doesn't make much sense to me. Or
TestMatch(val i: Int)
defines a set of types instead of a single type. Like template in C++:

template<int i>
class TestMatch{
//...
}


I was consufed by the line object

TestMatch extends TestMatch(10)

It looks like we extend
TestMatch(10)
which I thought was an object of type
TestMatch
created with a construcotr parameter
i = 10
. If I wrote

TestMatch extends TestMatch


it would not compile.

Answer

You are not extending an instance of TestMatch class. The below syntax just passes in constructor parameters to the base class.

 object TestMatch extends TestMatch(10)
Comments