Scala 2.10 TypeTag usage

前端 未结 4 1843
温柔的废话
温柔的废话 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条回答
  •  -上瘾入骨i
    2021-02-04 14:07

    actually you don't check the type of msg here, compiler will warn you that msg: T is erased, so all you are left checking is that type defined on TFilter is the same as a type defined on function f.

    I looks like pattern matching is "assisted" by Manifest and ClassTag, so msg: T is indeed a correct type. If you try it with primitives or List[T] it will not work correctly.

    val mFilter = new MFilter[Int]
    messages collect mFilter.f[Int] // res31: Seq[Int] = List()
    
    val messages = List(List(1), List("a"))
    val mFilter = new MFilter[List[Int]]
    messages collect mFilter.f[List[Int]] // res32: List[List[Int]] = List(List(1), List(a))
    

    Look at this discussion: http://grokbase.com/t/gg/scala-user/126p8eh1w0/how-to-make-typetag-work-in-a-pattern

    bug "Use TypeTags when pattern-matching otherwise erased types": here

提交回复
热议问题