Whats the difference between main and secondary methods in scala and how to execute mulitple functions in the scala class?

Viewed 38

I am beginner in scala coming from python. I am testing execution results from a Scala class in intellij. But I am confuse what to call these methods and how it is being executed in some cases. Please help me to understand 4 parts...

1 - Is calling secondary methods correct ???

object scala {
  def main(args: Array[String]): Unit = {
    val a : List[Int] =  List(1,2)
    val b = a.filter(x => x!=2)
    println("main result...")
    println(b)
  }
  def count_(args: Array[String]): Unit = { //2.  why it is not executable, what i am missing??? 
    val a = List("best", "a", "a", "b")
    val a_adv = a.map(x => (x,1))
    println("not main result")
    println(a_adv)
  }
  def count_ex(lst: List[String]): List[(String,Int)] = { //3. why its differnt from count_ ???
    val a_adv = lst.map(x => (x, 1))
    a_adv
  }
  println("not main external")
  println(count_ex(List("best", "a", "a", "b")))
}

output

not main external // missing count_ execution why???
List((best,1), (a,1), (a,1), (b,1))
main result...
List(1)
1 Answers

The body of your object, the code outside of any defs, constitutes the "static initializer" for the object. This code is executed at the time the class is loaded by the JVM (I'm assuming JVM here, but the semantics should also be the same for the other Scala targets, e.g. JS or Native).

The code inside the defs is not executed unless and until the method defined by the def is called.

If this class is handed to the JVM as the entrypoint (e.g. with java scala$ or similar), then after loading the class, the JVM will call the main method.

For example, if you modified main to include:

count_(args)

Then the count_ method would be called.

Since count_ex was called as part of the static initializer, it gets called at the time of class loading.

Note that you could move

println(count_ex(List("best", "a", "a", "b")))

before the def count_ex and it would still work.

Related