在 Scala 中处理嵌套 类

Dealing with nested classes in Scala

当我遇到以下错误时,我无法理解如何在 Scala esp 中使用嵌套的 classes:

class Action {
  val entityModelVar = new EntityModel
}

class EntityModel {
  class EntityLabel {
   ....
   }
}

上面的代码片段给出了我的 class 结构的想法。这里有两个代码块让我不明白它们是如何工作的。

val actionList=Array[Action](Action1,Action2)
..
val newLabels=actionList(i).test(doc)
actionList(i).retrain(newLabels) //error pointed here

**Error: type mismatch:
found   : Seq[a.entityModelVar.EntityLabel]
required   : Seq[_13.entityModelVar.EntityLabel] where _13:Action**

然而,下面的代码编译没有任何错误:

//This works fine
val a=actionList(i)
val newLabels=a.test(doc2)
a.retrain(newLabels)

此外,这里是 retrain 函数的定义:

 def retrain(labels:Seq[entityModelVar.EntityLabel])={
   entityModelVar.retrain(labels)
 }

EntityModel.retrain函数的签名:

def retrain(testLabels:Seq[EntityLabel]):Unit

问题是内部 class 必须属于外部 class 的同一个 实例 。但是 actionList(i) 是否保证在两次调用之间是同一个实例?编译器不确定(也许另一个线程摆弄它?谁知道 apply 到底做了什么?),所以它抱怨。 _13 是它希望在那里的临时变量的名称,以确保它 同一个实例。

你的下一个有效,因为编译器可以看到你调用 actionList(i) 一次,存储该实例,从中获取内部 class 然后应用它。

所以,这个故事的寓意是:你需要让编译器非常明显地知道你的内部 class 实例与其适当的外部 class 匹配,并且最好的方法是那就是将外部 class 存储在一个 val 中,如果你(或编译器)不注意它就不能改变。

(如果您分解参数块,您还可以指定单个变量的类型。因此,例如:def foo(m: EntityModel)(l: m.EntityLabel) 将是一种编写函数的方法,该函数采用外部 class 和一个里面一个与之对应。)