简体   繁体   中英

Pattern Matching on Generic Trait's Parameterized Type

Given the following trait:

trait Foo[_ <: Product] {}

How can I pattern match on Foo's generic type?

In other words, is there a way to get at Foo 's _ without using run-time reflection?

_作为类型参数的全部要点是指定类型是未知的

This is possible, and I still think it's a duplicate as noted by my comment, but wanted to show how you can do it anyway. Credit to om-nom-nom for the original answer:

  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")
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM