如何在 Scala 中对泛型类型进行模式匹配? [英] How to pattern match on generic type in Scala?

查看:67
本文介绍了如何在 Scala 中对泛型类型进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个泛型类Container:

Let's suppose we have a generic class Container:

case class Container[+A](value: A)

然后我们想要模式匹配 ContainerDoubleAnyContainer :

We then want to pattern match a Container with a Double and a Container of Any:

val double = Container(3.3)  
var container: Container[Any] = double

为此,我们通常会这样写:

To do this, we would normally write:

container match {  
  case c: Container[String] => println(c.value.toUpperCase)
  case c: Container[Double] => println(math.sqrt(c.value))  
  case _ => println("_")  
}

然而,编译器给出了两个警告,前两种情况各一个.例如,第一个警告说:类型模式 Container[String] 中的非变量类型参数 String 未选中,因为它被擦除消除了".由于擦除,在运行时无法区分不同类型的容器,并且会匹配第一个捕获.因此,Container[Double] 类型的容器将被第一种情况匹配,它捕获 Container[String] 对象,所以 toUpperCase将在 Double 上调用方法并抛出 java.lang.ClassCastException.

However, the compiler gives two warnings, one for each of the first two cases. For example, the first warning says: "non-variable type argument String in type pattern Container[String] is unchecked since it is eliminated by erasure". Because of the erasure, it is impossible during runtime to distinguish between different kinds of containers and the first catch will be matched. As a consequence, container of type Container[Double] will be matched by the first case, which catches Container[String] objects, so toUpperCase method will be called on a Double and a java.lang.ClassCastException will be thrown.

如何匹配由特定类型参数化的Container?

How to match a Container parametrized by a particular type?

推荐答案

一般来说 rarry 的答案是正确的,但是对于您的情况可以简化,因为您的容器仅包含泛型类型的单个值,因此您可以匹配直接在该值的类型上:

In general rarry's answer is correct, for your case however it can be simplified, because your container only contains a single value of a generic type, so you can match on that value's type directly:

container match {
  case Container(x: String) => println("string")
  case Container(x: Double) => println("double")
  case _ => println("w00t")
}

这篇关于如何在 Scala 中对泛型类型进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆