Scala 为什么我能';不要将case对象用作多态类型
以下代码未编译:Scala 为什么我能';不要将case对象用作多态类型,scala,Scala,以下代码未编译: 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对象用作多态类型呢? ^您试图实例化一个匿名类,给
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对象用作多态类型呢?
^您试图实例化一个匿名类,给它一个类型参数,但您的trait不接受一个
trait Yo
应该是trait Yo[type]
,其次您要将函数从AAA
扩展到String
,因此您必须为它提供一个apply方法,第三种情况是,您需要使用.type
,也称为单例类型注释:
trait AAA
case object BBB extends AAA
case object CCC extends AAA
trait Yo[TYPE] extends (AAA => String)
def bb = new Yo[BBB.type] {
override def apply(v1: AAA): String = ???
}
class OShow extends Show[O.type] {
override def show(a: O.type): String = "ahoy"
}
如果希望应用依赖于类型参数,则应执行以下操作:
trait Yo[TYPE] extends (TYPE => String)
def bb = new Yo[BBB.type] {
override def apply(v1: BBB.type): String = ???
}
编辑:我没有注意到您想要使其多态,在这种情况下,只需从trait中删除type参数,您无论如何都不会使用它:
trait AAA
case object BBB extends AAA
case object CCC extends AAA
trait Yo extends (AAA => String)
def bb = new Yo {
override def apply(v1: AAA): String = ???
}
我不确定你想要实现什么,但也许这就是你想要的
trait AAA
case class BBB(x: Int) extends AAA
case class CCC(x: String) extends AAA
trait Yo[T <: AAA] extends (T => String)
def bb = new Yo[BBB] { def apply(v1: BBB) = "BBB: " + v1.x}
def cc = new Yo[CCC] { def apply(v1: CCC) = "CCC: " + v1.x}
println(bb(BBB(5)), cc(CCC("foo"))) //(BBB: 5,CCC: foo)
特征AAA
案例类别BBB(x:Int)扩展了AAA
案例类别CCC(x:字符串)扩展AAA
特征Yo[T字符串)
defbb=newyo[BBB]{def apply(v1:BBB)=“BBB:+v1.x}
defcc=newyo[CCC]{def apply(v1:CCC)=“CCC:+v1.x}
println(bb(BBB(5)),cc(CCC(“foo”))/(BBB:5,CCC:foo)
正如@endeneu提到的,对于需要使用.type的case对象,也称为单例类型注释:
trait AAA
case object BBB extends AAA
case object CCC extends AAA
trait Yo[TYPE] extends (AAA => String)
def bb = new Yo[BBB.type] {
override def apply(v1: AAA): String = ???
}
class OShow extends Show[O.type] {
override def show(a: O.type): String = "ahoy"
}
你有你的答案,但你可以发布编译错误。因为其中的一个是“Yo不接受类型参数”,这将为你指明正确的方向。然后下一个错误是“找不到:类型BBB”这是对象不是类型的另一个强烈提示。依此类推。备注:
O.type
始终返回object
,无论对象实例如何。如果要(例如)将对象作为类型参数传递给特征,然后使用对象中定义的给定函数,则此操作无效。