类型的 Scala 模式匹配
Scala pattern matching for type
我写了下面的代码:
array(0).getClass match {
case Int.getClass =>
byeBuffer = ByteBuffer.allocate(4 * array.length)
case Long.getClass =>
ByteBuffer.allocate(8 * array.length)
case Float.getClass =>
ByteBuffer.allocate(4 * array.length)
case Double.getClass =>
ByteBuffer.allocate(8 * array.length)
case Boolean.getClass =>
ByteBuffer.allocate(1 * array.length)
但是 getClass
的过度使用对我来说感觉很笨拙。
有没有更好的写法?
您可以省略 getClass
并使用类型运算符 (:
):
val byteBuffer = 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)
}
另请注意,match
是 Scala 中的一个表达式,因此您可以将 byteBuffer
移到外部并将结果赋给它。这种功能性方法将使它更干净,并允许我们避免重新分配给 var
并使用 val
代替。
如果你想使用你匹配类型的变量,那么你可以简单地写成 l: Long
并使用 Long
类型的变量名称 l
.
我写了下面的代码:
array(0).getClass match {
case Int.getClass =>
byeBuffer = ByteBuffer.allocate(4 * array.length)
case Long.getClass =>
ByteBuffer.allocate(8 * array.length)
case Float.getClass =>
ByteBuffer.allocate(4 * array.length)
case Double.getClass =>
ByteBuffer.allocate(8 * array.length)
case Boolean.getClass =>
ByteBuffer.allocate(1 * array.length)
但是 getClass
的过度使用对我来说感觉很笨拙。
有没有更好的写法?
您可以省略 getClass
并使用类型运算符 (:
):
val byteBuffer = 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)
}
另请注意,match
是 Scala 中的一个表达式,因此您可以将 byteBuffer
移到外部并将结果赋给它。这种功能性方法将使它更干净,并允许我们避免重新分配给 var
并使用 val
代替。
如果你想使用你匹配类型的变量,那么你可以简单地写成 l: Long
并使用 Long
类型的变量名称 l
.