How can I match my own generic type?

I am trying to use pattern matching to detect a common type of my own custom type based on this answer .

The code provided by the author works as expected:

import scala.reflect.runtime.{universe => ru}

def matchList[A: ru.TypeTag](list: List[A]) = list match {
  case strlist: List[String @unchecked] if ru.typeOf[A] =:= ru.typeOf[String] => println("A list of strings!")
  case intlist: List[Int @unchecked] if ru.typeOf[A] =:= ru.typeOf[Int] => println("A list of ints!")
}

matchList(List("a", "b", "c"))
matchList(List(1,2,3))

correctly displays:

A list of strings!
A list of ints!

Now, based on this, I'm trying to apply the same pattern to determine the general type of my custom class Foo. Below is the code with a copy, except that it is Listused instead Foo:

import scala.reflect.runtime.{universe => ru}

class Foo[T](val data: T)

def matchFoo[A: ru.TypeTag](foo: Foo[A]) = {
  println("Is string = " + (ru.typeOf[A] =:= ru.typeOf[String]))
  println("Is int = " + (ru.typeOf[A] =:= ru.typeOf[Int]))
  foo match {
    case fooStr: Foo[String @unchecked] if ru.typeOf[A] =:= ru.typeOf[String] => println("Found String")
    case fooInt: Foo[Int @unchecked] if ru.typeOf[A] =:= ru.typeOf[Int] => println("Found Int")
  }
}

matchFoo(new Foo[String]("str"))
println("------------")
matchFoo(new Foo[Int](123))

Only this time it outputs not what I expected:

Is string = true
Is int = false
Found String
------------
Is string = false
Is int = true
Found String  // wth?

How will the second call matchFoo(new Foo[Int](123))display Found String? As you can see, I even explicitly printed out the conditions of the match, and they are in order.

Online Code: http://goo.gl/b5Ta7h

EDIT:

, :

def matchFoo[A: ru.TypeTag](foo: Foo[A]) = {
    val isString: Boolean = ru.typeOf[A] =:= ru.typeOf[String]
    val isInt: Boolean = ru.typeOf[A] =:= ru.typeOf[Int]
    println("Is string = " + isString)
    println("Is int = " + isInt)
    foo match {
      case fooStr: Foo[String @unchecked] if isString => println("Found String")
      case fooInt: Foo[Int @unchecked] if isInt => println("Found Int")
    }
}

: http://goo.gl/mLxYY2

, , . , , .

Scala? Scala SDK v. 2.11.5 JDK v. 1.8.0_25. CodingGround Scala SDK v. 2.10.3.

2:

Scala bugtracker . .

+4
1

, ( @unchecked?).

case fooStr: Foo[String @unchecked] if ru.typeOf[A] =:= ru.typeOf[String] =>
   println(implicitly[TypeTag[String]]) // will print TypeTag[Int]

TypeTag, ($evidence).

A () ru.definitions.IntTpe:

case fooStr: Foo[Int @unchecked] if ru.typeOf[A] =:= ru.definitions.IntTpe =>
   println("That an Int")
0

Source: https://habr.com/ru/post/1626552/


All Articles