加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

为什么我在scala比赛中有一个不可能的案例?

发布时间:2020-12-16 18:38:44 所属栏目:安全 来源:网络整理
导读:在下面的例子中,在第二种情况下,我会期望与第一种情况相同的编译错误,但它编译.为什么? object CaseMatching extends App { case class Id(value: Long) object Id { val zero = Id(0) } case class Name(value: String) case class IdName(id: Id,name: Na
在下面的例子中,在第二种情况下,我会期望与第一种情况相同的编译错误,但它编译.为什么?

object CaseMatching extends App {

  case class Id(value: Long)
  object Id { val zero = Id(0) }
  case class Name(value: String)
  case class IdName(id: Id,name: Name)

  IdName(Id(0),Name("A")) match {
    case IdName(_,Id(0)  ) => // does not compile (as expected)
    case IdName(_,Id.zero) => // does compile (but should not ?)
    case IdName(Id.zero,_) => println("OK") // this is OK and will match
    case _ =>
  }

}

为什么相关? – 我花了大部分时间来找出为什么从未遇到以下情况:case TreeEntry(_,Some(child),_,NodeType.DIR,_)那是因为NodeType是在第4场而不是在第5场.如果编译器告诉我,我会很感激!

解决方法

最短的答案:使Name最终足以说服编译器零不是一个.见 this issue和周围环境.

它会在类型测试上发出警告,这是一个isInstanceOf:

<console>:15: warning: fruitless type test: a value of type CaseMatching.Name cannot also be a CaseMatching.Id
           case IdName(_,_: Id) =>
                             ^

但是在测试平等时却不是,因为平等是普遍的.

这是另一个好的,案例IdName(_,Id)=>

<console>:15: error: pattern type is incompatible with expected type;
 found   : CaseMatching.Id.type
 required: CaseMatching.Name
Note: if you intended to match against the class,try `case _: Id`
           case IdName(_,Id) =>
                          ^

你想要的是:

scala> IdName(Id(0),Name("A")) match { case IdName(_,id: Id.zero.type) => }
<console>:21: warning: fruitless type test: a value of type Name cannot also be a Id (the underlying of Id.zero.type)
              IdName(Id(0),id: Id.zero.type) => }
                                                                         ^

单例类型仅包含该值,因此它使用eq进行测试;作为型式试验,它也警告说. (它在本周使用eq而不是equals.)

不确定这对你有多远,但是:

scala> :pa
// Entering paste mode (ctrl-D to finish)

sealed trait Id { def value: Long }
case class Nonzero(value: Long) extends Id
case object Zero extends Id { val value = 0L }
case class Name(value: String)
case class IdName(id: Id,name: Name)

// Exiting paste mode,now interpreting.

scala> IdName(Zero,Zero) => 1 }
<console>:14: error: pattern type is incompatible with expected type;
 found   : Zero.type
 required: Name
              IdName(Zero,Zero) => 1 }
                                                             ^

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读