Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't use a case object as a polymorphic type

Tags:

scala

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 ? ^

like image 961
Yann Moisan Avatar asked Mar 13 '15 12:03

Yann Moisan


2 Answers

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"
}
like image 118
Yann Moisan Avatar answered Nov 08 '22 22:11

Yann Moisan


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 = ???
}
like image 33
Ende Neu Avatar answered Nov 08 '22 22:11

Ende Neu