sharath chandra
sharath chandra

Reputation: 149

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

Upvotes: 1

Views: 161

Answers (2)

NieMaszNic
NieMaszNic

Reputation: 617

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.

Upvotes: 0

Chobeat
Chobeat

Reputation: 3535

I believe it's better to store the type T in a companion object if you want to keep a similar structure. Otherwise you could use a sum type and do something like this

sealed trait Colour

trait Red extends Colour

trait Green extends Colour

class RedClass extends Red
class GreenClass extends Green


def matchMethod(check:Colour) = {        

    check match {

        case Red => println("hello this is red")
        case Green => println("hello this is green")
    }
}

This way you can match exhaustively and safely, without weird type references.

Upvotes: 1

Related Questions