scala - 在特征体 Scala 中引用未初始化的值

标签 scala

为什么下面的代码不会引发引用错误?

trait T1 {
  println( "  in T1: x = " + x )
  val x=1
  println( "  in T1: x = " + x )
}

class C12 extends T1 {
  println( "  in C12: c = " + c )
  val c="C12"
  println( "  in C12: c = " + c )
}

new C12

相反,x 默认为 0,c 默认为 null。这在 scala 中是如何工作的?这些变量什么时候初始化?

最佳答案

As explained in the Scala Language Specification :

The scope of a name introduced by a declaration or definition is the whole statement sequence containing the binding. However, there is a restriction on forward references in blocks: In a statement sequence s1…sn making up a block, if a simple name in si refers to an entity defined by sj where j≥i, then for all sk between and including si and sj, sk cannot be a variable definition. If sk is a value definition, it must be lazy.

特征和类体不是 block ,因此这里没有前向引用限制。

When are these variables initialized?

语句(包括 val 初始化)只是按顺序执行。

关于scala - 在特征体 Scala 中引用未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38217009/

相关文章:

scala - 将行合并到列表中以获得 SPARK 中的相似值

scala - 为什么不围绕整数溢出进行 Scala 设计?

scala - 折叠选项列表以查找第一个或最后一个

scala - 如何让 Scala BigDecimal 显示大量数字?

xml - 如何在 Scala XML 输出中生成整数文字作为属性?

scala - 在编译的 Scala 中,bitmap$0 字段是什么?

scala - scala 是否忽略函数签名中的类型?

Scala Play框架2.1派生类

python - 获取保存 Parquet 文件的默认 HDFS 路径

scala - Akka微服务之间如何共享通信模型?