3

Why is a field of an object initialised every time the field is used? My expectation was that an instance of an Scala Object, in my example an instance of P, is created once since it belongs to a Scala Object. Running the code below it look like this is not the case. An instance of P is created every time a method on P is called. I could not find any explanation for this behaviour. Can anybody help? Thanks.

object LoadingTest {

  println("create Object")
   def p = new P()

  def main(args: Array[String]) {
    p.printIt()
    p.printIt()
  }
}

class P(){
  println("create P")
  def printIt()={
    println("print it")
  }

}

Output:

create Object
create P
print it
create P
print it
rustyfinger
  • 199
  • 2
  • 7
  • 2
    See also http://stackoverflow.com/questions/9449474/def-vs-val-vs-lazy-val-evaluation-in-scala for a quick rundown of the differences between def, val, and lazy val. – whaley Feb 26 '15 at 01:19

1 Answers1

7

It's because you have def p = new P(). By defining this with def, you are defining a method. So every time you reference p, it's calling the method, thus instantiating a new P.

You want val p = new P(), which will ensure that the object is instantiated just once, stored as a val, and reused each time it is referenced.

dhg
  • 52,383
  • 8
  • 123
  • 144
  • Thanks for the quick response. I am just getting started with Scala, in a Java developers eye something as short as def p = new P() does not look like a method at all. – rustyfinger Feb 25 '15 at 23:42