获取图案加工中默认案例的类型



我想知道当触发默认情况时,模式匹配中对象的类型。

这就是我尝试过的:

byeBuffer = array(0) match {
case _: Int =>
ByteBuffer.allocate(4 * array.length)
case _: Long =>
ByteBuffer.allocate(8 * array.length)
case _: Float =>
ByteBuffer.allocate(4 * array.length)
case _: Double =>
ByteBuffer.allocate(8 * array.length)
case _: Boolean =>
ByteBuffer.allocate(1 * array.length)
case _ => throw new UnsupportedOperationException("Type not supported: " + _.getClass())
}

但上面写着"无法解析符号getClass"。

在这种情况下,_意味着不会为匹配的值分配标识符。

您可以将_替换为任何不带类型的标识符,并且它仍将匹配剩余的情况:

byeBuffer = array(0) match {
case _: Int =>
ByteBuffer.allocate(4 * array.length)
case _: Long =>
ByteBuffer.allocate(8 * array.length)
case _: Float =>
ByteBuffer.allocate(4 * array.length)
case _: Double =>
ByteBuffer.allocate(8 * array.length)
case _: Boolean =>
ByteBuffer.allocate(1 * array.length)
case default => throw new UnsupportedOperationException(s"Type not supported: ${default.getClass()}")
}

对下划线在中的工作方式有一个常见的错误理解

case _ => throw new UnsupportedOperationException("Type not supported: " + _.getClass())

这两个下划线彼此不对应,而是扩展为类似的内容

case _ => throw new UnsupportedOperationException(x => ("Type not supported: " + x.getClass()))

也就是说,第二个下划线被视为匿名函数占位符语法,其作用域是第一个括括号。

最新更新