scalapattern-matchingscala-reflect

Scala type pattern matching


I want to implement a pattern matching over types of case class. Caurrently I have this idea in mind:

val T = typeOf[Int]
val S = typeOf[String]
// other primitive types
val O = typeOf[Option[_]]  // doesn't work for all generic types
val X = typeOf[AnyRef]     // doesn't work at all

typeOf[A].members.filter(!_.isMethod).map(_.typeSignature).foreach {
  case T => println("int")
  case S => println("string")
  // other primitive types
  case O => println("option")
  case X => println("other")
}

But I have a two problems:

  1. How to create a type which would match any Option, List or Map in spite of there generic types?
  2. How to create a type which would match any other custom types?

Any ideas would be appreciated.


Solution

  • The solution which I was able to find:

    val T = typeOf[Int]
    val S = typeOf[String]
    
    typeOf[A].members.filter(!_.isMethod).map(_.typeSignature).foreach {
      case T => println("int")
      case S => println("string")
      // other primitive types
      case x if x.erasure =:= typeOf[Option[Any]] => println("option")
      case x if x <:< typeOf[AnyRef] => println("other")
    }