stella stella - 2 months ago 5x
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
. 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
which I thought was an object of type
created with a construcotr parameter
i = 10
. If I wrote

TestMatch extends TestMatch

it would not compile.


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)