为什么我不能使用 case 对象作为多态类型 [英] Why I can't use a case object as a polymorphic type

查看:59
本文介绍了为什么我不能使用 case 对象作为多态类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译:

  case object O

  trait Show[A] {def show(a: A) : String}

  class OShow extends Show[O] {
    override def show(a: O): String = "ahoy"
  }

编译错误是

Error: not found: type O
  class OShow extends Show[O] {

那么,如何使用 case 对象作为多态类型?^

So, how to use a case object as a polymorphic type ? ^

推荐答案

正如@endeneu 提到的,对于 case 对象,您需要使用 .type,也称为单例类型注释:

As @endeneu mention it, for case objects you need to use .type, also called singleton type annotation:

class OShow extends Show[O.type] {
  override def show(a: O.type): String = "ahoy"
}

这篇关于为什么我不能使用 case 对象作为多态类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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