I am writing scala in Intellij, the following codes can run correctly, but the IDE gives a syntax error report, Intellij recognises c.value as generic type A in both cases :
object TypeTagTest extends App {
case class Container[+A](value: A)
matchContainer(Container("1"))
matchContainer(Container(1.0))
matchContainer1(Container("20"))
matchContainer(Container(16.0))
def matchContainer[A: TypeTag](c: Container[A]) = c match {
case c: Container[String @unchecked] if typeOf[A] <:< typeOf[String] => println("type of string: " + c.value.toUpperCase)
case c: Container[Double @unchecked] if typeOf[A] <:< typeOf[Double] => println("type of double: " + math.sqrt(c.value))
case c: Container[_] => println("other")
}
def matchContainer1[A: ClassTag](c: Container[A]) = c match {
case c: Container[String @unchecked] if classTag[A] == classTag[String] => println("type of string: " + c.value.toUpperCase)
case c: Container[Double @unchecked] if classTag[A] == classTag[Double] => println("type of double: " + math.sqrt(c.value))
case c: Container[_] => println("other")
}
}
The results: type of string: 1 type of double: 1.0 type of string: 20 type of double: 4.0
Thanks for the help.
Aucun commentaire:
Enregistrer un commentaire