Reputation: 3602
I have a simple class in Scala. I want to init some data when class is created. This is my code:
class SomeClass(someSeq: Seq[Int]) {
val someMap = scala.collection.mutable.Map.empty[Int, Set[String]]
init()
def init(): Unit = {
println("init")
}
override def getData(aValue: Int): Set[String] = {
println("I was called")
}
}
And the code that runs it:
def someClass = new SomeClass(a)
for (i <- 1 to 3) {
someClass.getData(i)
}
This is the output:
init
init
I was called
init
I was called
init
I was called
The code in "Init" initializes "someMap".
For some reason, the Init method get called every time I call the method "getData". What am I doing wrong?
Upvotes: 0
Views: 203
Reputation: 41769
def someClass = new SomeClass(a)
your def
defines a method. Invoking the method calls new SomeCLass(a)
.
for (i <- 1 to 3) {
someClass.getData(i)
}
Your for loop calls the someClass
method three times. Each of those invocations calls new SomeClass(a)
. The constructor calls init
each time. someClass
then returns the new instance, and getData
is called on that.
So it's not calling getData
that causes init
to be called. It's calling new SomeClass(a)
Try
val someClass = new SomeClass(a)
instead. That will call new SomeClass(a)
once and assign the result to someClass
.
Also, your posted code doesn't even compile (because getData's body doesn't return the correct type)
Upvotes: 3