Scala:检查 2 个变量是否属于同一类型

Scala: Checking if 2 variables are of the same type

所以我一直在尝试检查如何检查 2 个变量 x 和 y 是否属于同一类型。

人们发布了关于 =:= 的帖子,但似乎只检查变量是否为 X 类型。

是否可以使用模式匹配中的一些技巧?

谢谢。

x.getClass() == y.getClass() 

适用于 运行 时,不适用于编译时。由于它是 post 类型擦除,任何类型参数(Java 泛型)都将消失 - 所以 List[Int].getClass() == List[String].getClass()。这可能有用也可能没用!

对于编译时的静态类型检查:

def sameType[T, U](a: T, b: U)(implicit evidence: T =:= U) = true

然后

sameType("abc", "cde") // Returns true
sameType("abc", 123)   // Does not compile