在惰性求值中解释这种类型不匹配 [英] Explain this type-mismatch in lazy evaluation

查看:43
本文介绍了在惰性求值中解释这种类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图理解这个评论,我写了以下代码:

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 中)<:java.lang.Object使用 ScalaObject{lazy def Mother: Chicken} 需要:(一些其他)鸡蛋(在惰性值 scala_repl_value) forSome { type (someother)Egg(inlazy value scala_repl_value) <: java.lang.Object withScalaObject{懒惰的妈妈:鸡};类型鸡<:java.lang.Object with ScalaObject{lazy def offspring: (someother)Egg(inlazy value scala_repl_value)} } 对象RequestResult$line16$object {

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?

推荐答案

你在 breakfast 函数的作用域内定义了 ChickenEgg 类,所以他们在外面看不到,即除了 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
}

这篇关于在惰性求值中解释这种类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆