EdgeRover
EdgeRover

Reputation: 195

Scala: Call a method as part of the constructor

I have a class in Scala with two argument for its constructor:

class SomeClass (x:Int, y:Int) {
}

I need to expand the constructor so when an object of this class is initialized, some method is called, which uses the value of x defined in the primary constructor defaulted by Scala, and then outputs a value z:

def defineInputs(): Int = {
    val z = x + 1
    z
}

I want the value of z to be accessible publicly to all methods in the class, just like x and y are.

Can you please help me with this ?

Upvotes: 0

Views: 1327

Answers (1)

Eric
Eric

Reputation: 1114

You can simply define a val inside the class, like so:

scala> :pa
// Entering paste mode (ctrl-D to finish)

class SomeClass(x: Int, y: Int) {
  val z = x + 1
}

new SomeClass(0, 0).z

// Exiting paste mode, now interpreting.

defined class SomeClass
res0: Int = 1

You could also use a case class:

scala> case class SomeClass(x: Int, y: Int) {
     |   val z = x + 1
     | }
defined class SomeClass

scala> SomeClass(0, 0).z
res0: Int = 1

Upvotes: 3

Related Questions