python
python

Reputation: 1940

Scala debugging

I am new to Scala and I have setup an environment with IntelliJ. I found out one problem I could not explain, here is the code:

object HelloWorld extends App{
    print("before")
    var aMap = Map("A"->1, "B"->2)
    println("after")
    println(aMap)
}

I noticed that println(aMap) could clearly print out the Map("A"->1, "B"->2), so I want to debug and found out if Map has implemented an funcn which will be called by println, using IntelliJ. So I set a debug point on:

println(aMap)

When I "step into" the function, it seems var aMap = Map("A"->1, "B"->2) was called again! So , whats the reason that this was called a second time?

Upvotes: 2

Views: 1978

Answers (1)

ggovan
ggovan

Reputation: 1927

All top level fields (var/val) are also turned into methods to help with the concept of a uniform access principle.

var map = Map(1->2)
val list = List(1,2)

becomes

var map = Map(1->2)
def map = map
def map_=(nValue: Map[Int.Int]) {map = nValue}

val list = List(1,2)
def list = list
// No setters for vals

So when you call println(aMap) it uses the hidden accessor method to get the value of aMap.

This is all happening because you are at the top-level of the object. Had this been in a method:

object HelloWorld extends App{
  def run() {
    print("before")
    var aMap = Map("A"->1, "B"->2)
    println("after")
    println(aMap)
  }
  run()
}

Then the var aMap would be a local variable and not use an indirect lookup.

Upvotes: 3

Related Questions