通用特征参数化类型的模式匹配

时间:2015-01-09 19:05:57

标签: scala

鉴于以下特点:

trait Foo[_ <: Product] {}

如何在Foo的泛型类型上进行模式匹配?

换句话说,有没有办法在不使用运行时反射的情况下到达Foo的{​​{1}}?

2 个答案:

答案 0 :(得分:1)

作为类型参数的_的重点是指定类型为 unknown

答案 1 :(得分:1)

这是可能的,我仍然认为这是我的评论所指出的重复,但是想要展示你如何能够做到这一点。归功于om-nom-nom的原始答案:

  trait Foo[_ <: Product]

  case class Bar(i:Int)
  case class Baz(s:String)  

  val fooBar = new Foo[Bar]{}
  val fooBaz = new Foo[Baz]{}

  checkType(fooBar)
  checkType(fooBaz)

  def checkType[T <: Product : TypeTag](foo:Foo[T]){
    foo match{
      case f if typeOf[T] <:< typeOf[Bar] => println("its a bar")
      case f if typeOf[T] <:< typeOf[Baz] => println("its a baz")
    }
  }
相关问题