sharath chandra sharath chandra - 1 month ago 17
Scala Question

Type matching in scala

object Test1 extends App {

object specificTypes extends Enumeration {
type specificTypes = Value
val Red = Value
val Green = Value
val Blue = Value
}

abstract class outer {
type T <: Test1.specificTypes.Value
def pr(w: T)
}

class red extends outer {
type T = Test1.specificTypes.Red // Getting Error Here, type Red is not a member of object Test1.specificTypes
def pr(w: T) = println("hello red")
}

val r = new red
r.pr(Test1.specificTypes.Red)

}


type Red is not a member of object Test1.specificTypes , How to solve It, Where i am going Wrong

Answer

type T = Test1.specificTypes.Red doesn't assign the type. It tries to assign the value as a type, which of course does not compile.

How about this?

object Test1 extends App {


  object specificTypes extends Enumeration {
    type specificTypes = Value
    val Red = Value
    val Green = Value
    val Blue = Value
  }

  abstract class outer {
    type T <: Test1.specificTypes.Value
    def pr(w: T)
  }

  class red extends outer {
    type T = Test1.specificTypes.Red.type //IMPORTANT THING!
    def pr(w: T) = println("hello red")
  }
  class blue extends outer {
    type T = Test1.specificTypes.Blue.type //IMPORTANT THING!
    def pr(w: T) = println("hello blue")
  }

  val r = new red
  //r.pr(Test1.specificTypes.Blue) // compilation error
  /*
    Error:(23, 28) type mismatch;
   found   : Test1.specificTypes.Blue.type (with underlying type Test1.specificTypes.Value)
   required: Test1.r.T
      (which expands to)  Test1.specificTypes.Red.type
    r.pr(Test1.specificTypes.Blue)
   */


  val b = new blue
  b.pr(Test1.specificTypes.Blue) // compiles, prints hello blue
}

BUT, for you case (like you mentioned)

I have some classes with type , I want to differentiate the classes By Type in pattern matching

I would use a simple sealed trait, just like in the Chobeat's answer.