scala - 如何匹配Scala中数组的类型?
问题描述
给定一个接收参数的函数,arr : Array[Any]
我如何匹配Any
模式中的类型?更重要的是,如何同时匹配多个案例?
目前我有
def matchType (arr: Array[Any]) = {
arr match {
case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => arr.map(*...*);
case b: Array[Byte] => print("byte")
case _ => print("unknown")
}
}
无法编译
cmd8.sc:4: scrutinee is incompatible with pattern type;
found : Array[Int]
required: Array[Any]
Note: Int <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
^
cmd8.sc:4: scrutinee is incompatible with pattern type;
found : Array[Long]
required: Array[Any]
Note: Long <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
^
cmd8.sc:4: scrutinee is incompatible with pattern type;
found : Array[Double]
required: Array[Any]
Note: Double <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
case a @ ( _: Array[Int] | _: Array[Long] | _: Array[Double] ) => print("numerical");
^
cmd8.sc:5: scrutinee is incompatible with pattern type;
found : Array[Byte]
required: Array[Any]
Note: Byte <: Any, but class Array is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
case b: Array[Byte] => print("byte")
^
Compilation Failed
解决方案
您无法匹配整体Array
,但可以依次匹配每个元素:
def matchType (arr: Array[_]) =
arr.foreach{
case _: Double | _: Float => println("floating")
case i: Int => println("int")
case b: Byte => println("byte")
case _ => println("other")
}
由于Array[Any]
可能混合了基础类型,因此您无法Array
在不依次检查每个元素的情况下转换为另一种类型。
推荐阅读
- scala - 无法在 Spark Scala 中将 Seq[String] 传递给 .parquet
- android - Android RelativeLayout:显示 ConstraintLayouts 列表
- android - 如何防止再次设置视图模型,在返回片段导航
- swift - pushViewController 中转的上一屏是空白的
- django - 使用确认提示删除视图 - Django
- azure-resource-manager - ARM 参数数组中的密钥库引用
- assembly - PUSH 的 Intel REX 编码
- spring-security - 记住没有 HTTP 会话的目标 URL
- tsql - where 子句中的 case 表达式以包含多个值
- django - Drf unique_together 防止视图集中的破坏