Alo*_*lon 2 functional-programming scala pattern-matching
我想知道触发默认情况时模式匹配中对象的类型。
这是我尝试过的:
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())
}
Run Code Online (Sandbox Code Playgroud)
但它说“无法解析符号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()}")
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35 次 |
| 最近记录: |