Reputation: 44436
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
}
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:
error: type mismatch; found : Egg(in lazy value scala_repl_value) where type Egg(in lazy value scala_repl_value) <: java.lang.Object with ScalaObject{lazy def mother: Chicken} required: (some other)Egg(in lazy value scala_repl_value) forSome { type (some other)Egg(in lazy value scala_repl_value) <: java.lang.Object with ScalaObject{lazy def mother: Chicken}; type Chicken <: java.lang.Object with ScalaObject{lazy def offspring: (some other)Egg(in lazy value scala_repl_value)} } object RequestResult$line16$object {
Can somebody explain what's going on here?
Upvotes: 4
Views: 756
Reputation: 10776
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
}
Upvotes: 4