【发布时间】:2020-08-17 01:18:09
【问题描述】:
我有以下代码:
val obj: Int = 5;
var objType: Class[_] = obj.getClass
objType match {
case _: Int =>
byeBuffer.putInt(asInstanceOf[Int])
case _: Long =>
byeBuffer.putLong(asInstanceOf[Long])
case _: Float =>
byeBuffer.putFloat(asInstanceOf[Float])
case _: Double =>
byeBuffer.putDouble(asInstanceOf[Double])
case _: Boolean => {
val byte = if (asInstanceOf[Boolean]) 1 else 0
byeBuffer.put(byte.asInstanceOf[Byte])
}
case default => throw new UnsupportedOperationException("Type not supported: " + default.getClass)
}
此代码已损坏。但是,如果我使用 obj 而不是 objType 那么它会起作用。但我想在模式匹配中专门使用 objType。
【问题讨论】:
-
这能回答你的问题吗? Pattern matching on Class[_] type?
标签: scala functional-programming pattern-matching