4

I'm wondering if using a generic type, known at runtime through ClassTag or Manifest is not in fact a code smell, leading to unpredictable results.

Here is a example of what can happen:

import scala.reflect._

trait BaseTrait 

trait OtherTrait 

def filter[T](any: AnyRef)(implicit ct: ClassTag[T]): Option[T] = 
  any match {
    case t: T => Option(t)
    case _    => None
  }

val baseOnly: BaseTrait = new BaseTrait {}

// None expected, None found
println(filter[OtherTrait](baseOnly)) 
// None expected,    Some(baseOnly) found
println(filter[BaseTrait with OtherTrait](baseOnly)) 

I do understand the reasons why (Classtag capturing only BaseTrait when BaseTrait with OtherTrait is provided). I also do understand that Manifests have the same behaviour, and that TypeTags can't save me, because you can't check an instance at runtime against a TYpeTag.

Then the question is : should we not expected the compiler to throw a warning ? Or did I miss something ? (I presume the answer is 'you missed something')

Kam
  • 41
  • 2
  • `Classtag capturing only BaseTrait when BaseTrait with OtherTrait is provided` Not true. It captures both, which is an anonymous compound type. `you can't check an instance at runtime against a TYpeTag` Yes you can and that's what TypeTag had been designed for. – SwiftMango Dec 07 '20 at 18:55

0 Answers0