问题描述
试图理解这个评论,我写了以下代码:
Trying to grok this comment, I wrote the following code:
def breakfast : AnyRef = {
class Chicken (e: =>Egg) {
lazy val offspring = e
}
class Egg (c: =>Chicken) {
lazy val mother = c
}
lazy val (egg: Egg, chicken: Chicken) = (new Egg(chicken),
new Chicken(egg))
egg
}
它可以工作,并且完全符合您的希望.我不明白的是,为什么 : AnyRef
是必要的?如果不包括在内,编译器(至少是 2.8 编译器)会死得很惨:
And it works and it does exactly what you'd hope it'd do. What I don't get is, why is the : AnyRef
necessary? If it's not included, the compiler (the 2.8 compiler at least) dies a horrible death:
错误:类型不匹配;found : Egg(在惰性值 scala_repl_value 中)其中类型 Egg(在惰性值 scala_repl_value 中)
有人能解释一下这里发生了什么吗?
Can somebody explain what's going on here?
推荐答案
你在 breakfast
函数的作用域内定义了 Chicken
和 Egg
类,所以他们在外面看不到,即除了 breakfast
没有人不知道这些课程.在 Scala 2.9 中,这个片段实际上有效,并且 breakfast
函数的返回值定义为
You define classes Chicken
and Egg
in scope of breakfast
function, so they are not seen outside i.e. nobody except breakfast
don't know these classes. In Scala 2.9 this snippet actually works, and breakfast
function's return value is defined as
def breakfast: Egg forSome { type Egg <: java.lang.object with scalaobject{lazy val mother: chicken}; type chicken <
当类定义在函数之外时,一切都按预期工作
When classes defined outside of function everything works as expected
class Chicken(e: => Egg) {
lazy val offspring = e
}
class Egg(c: => Chicken) {
lazy val mother = c
}
def breakfast: Egg = {
lazy val (egg: Egg, chicken: Chicken) =
(new Egg(chicken), new Chicken(egg))
egg
}
这篇关于在惰性求值中解释这种类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!