Prassi
Prassi

Reputation: 117

Scala main constructor initialisation

Why does the following class throw an exception at initialisation:

class Test {
  val att = throw new Exception("")
}
new Test() // raises Exception

Whereas the following class doesn't?

class Test {
  val att = Seq((1, "a")).groupBy(_._1).mapValues(throw new Exception(""))
}
new Test() // doesn't raise Exception
(new Test()).att // raises Exception

Upvotes: 1

Views: 70

Answers (1)

m_vemuri
m_vemuri

Reputation: 792

vals defined in a class are evaluated on instantiation of the class.

Since the val defined by this class has a throws keyword, it will throw an exception upon instantiation. Actually, all the examples will throw an exception.

To avoid this problem, define the val att as a new Exception but don't throw it upon creation.


class Test {
  val att: Exception = new Exception("test")
}


new Test()             // doesn't raise Exception
(new Test()).att       // doesn't Exception

throw (new Test().att) // throws exception

Upvotes: 1

Related Questions