nam
nam

Reputation: 3632

My function can not find a class but a case class inside the same Object

If I change the code below from class to case class then I works. I don't know why

object Test {
  trait T {
    var l = {
      println("l in T initialized")
      "OK"
    }
  }

  class MyClass(x: Int) extends T

  def testTrait() = {
    val t = MyClass(1)

  }

}

Upvotes: 0

Views: 80

Answers (1)

Zoltán
Zoltán

Reputation: 22166

If it's not a case class, you need to instantiate it as

val t = new MyClass(1)

i.e. call its constructor.

The reason why you don't need the new keyword when it's a case class is that declaring it a case class implicitly defines an apply method in your class's companion object; i.e. you get this for free:

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

The apply method is syntactic sugar in scala which allows for this shorthand notation MyClass(1).

You also get other stuff for free, e.g. an unapply method, an equals method which implements structural equality and a toString method. See more here: http://docs.scala-lang.org/tutorials/tour/case-classes.html

Upvotes: 4

Related Questions