简体   繁体   中英

Scala initialize a constructor called more than once

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM