scala类中的语句

时间:2017-06-23 15:28:52

标签: scala

除了方法和字段之外,您还可以直接在scala类中放置一个语句,如下所示:

class printHelloWorld {
  val x = 1
  println("Hello World")
  val y = 2
}

object callHelloWrold extends App {
  val helloWorldObj = new printHelloWorld
}

创建新对象时会打印“Hello World”。在scala中调用的这种语句是什么?这个语句是在类构造函数和val x = 1之后,还是在val y = 2之前调用的?如果是这样,编译器如何设法做到这一点?它是否创建了一个包含所有这些语句的匿名方法?

1 个答案:

答案 0 :(得分:2)

x的定义,println和y的定义都是您定义的类的主构造函数中的所有语句。 x和y是可以在创建的新对象上访问的成员变量。有关交错def,val和printlns

的一些示例,请参见下面的repl会话
Welcome to the Ammonite Repl 1.0.0-RC7
(Scala 2.12.2 Java 1.8.0_77)
If you like Ammonite, please support our development at www.patreon.com/lihaoyi
mshelton-mshelton@ class Test {
                   val x = 1
                   def a = 5
                   println("defs and vals and constructors and oh my")
                   val z = 3
                   def g(): Unit = {println("sup")}
                   }
defined class Test
mshelton-mshelton@ val test = new Test()
defs and vals and constructors and oh my
test: Test = ammonite.$sess.cmd0$Test@743d0d44
mshelton-mshelton@ test.g()
sup

mshelton-mshelton@ test.a
res3: Int = 5
mshelton-mshelton@ test.x
res4: Int = 1
mshelton-mshelton@