[英]class constructor refer back to a type member of the class
I am trying to implement a case class which is meant to describe an automaton. 我正在尝试实现一个用于描述自动机的案例类。 I am currently doing following: 我目前正在执行以下操作:
case class Automaton(alphabet: Set[String], initial: String, finish: Set[String],
transitions: Map[String, self.Transition] { self =>
trait Transition
// concrete things omitted
}
Note that how I want transitions
to be defined. 请注意,我希望如何定义transitions
。 I hope that makes sense to you why I want to implement in such way. 我希望这对您有意义,为什么我要以这种方式实施。 However, when I tried to compile, compiler reported following error: 但是,当我尝试编译时,编译器报告以下错误:
Error:(21, 47) not found: value self
transitions: Map[String, self.Transition]) {
I understand the error. 我了解错误。 But how then can I force the transition is the exact transition belongs to the automaton I am describing? 但是,我该如何强制过渡是确切的过渡属于我所描述的自动机呢? Any idea how to get around this? 任何想法如何解决这个问题?
I got the problem myself. 我自己遇到了问题。 Sure this cannot type check. 确保这不能键入检查。 Even if it did, I won't be able to instantiate any instance of this type. 即使这样做,我也无法实例化此类型的任何实例。 To get away with this, I need to define dependent function. 为了解决这个问题,我需要定义依赖函数。
trait DepFunc {
def apply(automaton: Automaton): Map[String, automaton.Transition]
}
Then inside of the body of the case class, I then can construct the transitions
: 然后,在case类的主体内部,可以构造transitions
:
val transitions: Map[String, self.Transition] = transitionsGen(this)
One extra observation is, it turns out that Scala's type system is not powerful enough to describe a dependent function. 另一个发现是,Scala的类型系统不够强大,无法描述依赖函数。 For example, the trait DepFunc
above cannot be described by Function1
, that is because at type level, scala disallows to refer to a variable name. 例如,上面的特征DepFunc
无法用Function1
描述,这是因为在类型级别,scala不允许引用变量名。 This gives a concrete feeling of scala's incapability of handling dependent types. 这给人一种Scala无法处理依赖类型的具体感觉。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.