Scala 2.10 TypeTag usage

前端 未结 4 1842
温柔的废话
温柔的废话 2021-02-04 13:27

I\'m digging new scala reflection api and can\'t figure out why the following snippet doesn\'t work as expected. Given hierarchy (tried to simplify as much as I can):

         


        
4条回答
  •  失恋的感觉
    2021-02-04 14:10

    Just for fun:

    import scala.reflect._
    import scala.reflect.runtime.{currentMirror=>cm,universe=>ru}
    import ru._
    
    object Test extends App {
      type MyTag[A] = TypeTag[A]
      //type MyTag[A] = ClassTag[A]
    
      trait TF[A] {
        implicit def t: MyTag[A]
    
        def f[T <: A: MyTag]: PartialFunction[Any, A] = {
          //case msg: T => msg            // ok for ClassTag
          case msg: T @unchecked if matching[T](msg) => msg
          //case msg: T if typeOf[T] =:= typeOf[A] => msg
        }
        def matching[T](a: Any)(implicit tt: TypeTag[T]) =
          (cm reflect a).symbol.toType weak_<:< tt.tpe
      }
    
      case class TFilter[A: MyTag]() extends TF[A] {
        def t = implicitly[MyTag[A]]
      }
    
      trait Foo { def x: Int }
      case class Bar(x: Int) extends Foo
      case class Baz(x: Int) extends Foo
    
      val messages = Seq(1, Bar(0), "hello", Baz(1))
      println(messages collect TFilter[Foo].f[Foo])
      println(messages collect TFilter[Foo].f[Bar])
    }
    

提交回复
热议问题