The following code doesn't compile :
case object O
trait Show[A] {def show(a: A) : String}
class OShow extends Show[O] {
override def show(a: O): String = "ahoy"
}
The compilation error is
Error: not found: type O
class OShow extends Show[O] {
So, how to use a case object as a polymorphic 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"
}
You are trying to instantiate an anonymous class giving it a type parameter, but your trait doesn't take one trait Yo
should be trait Yo[TYPE]
, second you are extending a function from AAA
to String
so you have to provide an apply method for it, third for case objects you need to use .type
, also called singleton type annotation:
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 = ???
}
If you wanted the apply to be dependent on the type parameter you should have done something like this:
trait Yo[TYPE] extends (TYPE => String)
def bb = new Yo[BBB.type] {
override def apply(v1: BBB.type): String = ???
}
Edit: I didn't notice you wanted to make it polymorphic, in that case just remove the type parameter from the trait, you are not using it anyway:
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 = ???
}
I'm not sure what you wanted to achieve but maybe this is what you are looking for.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.