[英]Whats the difference between main and secondary methods in scala and how to execute mulitple functions in the scala class?
I am beginner in scala coming from python.我是来自 python 的 scala 的初学者。 I am testing execution results from a Scala class in
intellij
.我正在测试 intellij 中
intellij
class 的执行结果。 But I am confuse what to call these methods
and how it is being executed in some cases.但是我很困惑如何调用这些
methods
以及在某些情况下它是如何执行的。 Please help me to understand 4
parts...请帮助我理解
4
部分...
1 - Is calling secondary methods
correct??? 1 - 调用
secondary methods
是否正确???
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 output
not main external // missing count_ execution why???
List((best,1), (a,1), (a,1), (b,1))
main result...
List(1)
The body of your object
, the code outside of any def
s, constitutes the "static initializer" for the object. object
的主体,任何def
之外的代码,构成 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, eg JS or Native). 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, eg JS or Native).
The code inside the def
s is not executed unless and until the method defined by the def
is called.除非调用
def
定义的方法,否则不会执行def
中的代码。
If this class is handed to the JVM as the entrypoint (eg with java scala$
or similar), then after loading the class, the JVM will call the main
method. If this class is handed to the JVM as the entrypoint (eg 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:例如,如果您修改
main
以包括:
count_(args)
Then the count_
method would be called.然后会调用
count_
方法。
Since count_ex
was called as part of the static initializer, it gets called at the time of class loading.由于
count_ex
作为 static 初始化程序的一部分被调用,它在 class 加载时被调用。
Note that you could move请注意,您可以移动
println(count_ex(List("best", "a", "a", "b")))
before the def count_ex
and it would still work.在
def count_ex
之前,它仍然可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.