获取模式匹配中默认情况的类型
Getting the type of the default case in pattern maching
我想知道触发default case时模式匹配对象的类型
这是我试过的:
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())
}
但是它说 "Cannot resolve symbol 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()))
即第二个下划线被视为匿名函数占位符语法,其范围是第一个括号。
我想知道触发default case时模式匹配对象的类型
这是我试过的:
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())
}
但是它说 "Cannot resolve symbol 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()))
即第二个下划线被视为匿名函数占位符语法,其范围是第一个括号。