Scala 向Tuple2投射任何
我有一个Scala函数,它传递“Any”类型的消息。在大多数情况下,它将是一个大小为2的元组。接收此消息的函数需要查看元组元素的特定类型:Scala 向Tuple2投射任何,scala,casting,tuples,Scala,Casting,Tuples,我有一个Scala函数,它传递“Any”类型的消息。在大多数情况下,它将是一个大小为2的元组。接收此消息的函数需要查看元组元素的特定类型: main() { // call to function // msg is of type Any. func (msg) } 现在在我的功能中 function (msg : Any) { String inputType = msg.getClass.getCanonicalName if (inputType.compar
main() {
// call to function
// msg is of type Any.
func (msg)
}
现在在我的功能中
function (msg : Any) {
String inputType = msg.getClass.getCanonicalName
if (inputType.compareTo("scala.Tuple2") == 0) {
// I now know that the input to the function is a tuple..I want to extract the type of each element in this tuple.
//something like:
var tuple = msg.asInstanceof(scala.Tuple2) // This line gives an error. I want to cast object of Type Any to a tuple.
var 1type = tuple._1.getClass.getCanonicalName
var 2type = tuple._2.getClass.getCanonicalName
}
}
模式匹配
msg match {
case (x,y) => ...
}
你为什么不直接用它呢
在使用Scala构建工具版本sbt-0.13.8进行测试后,我刚刚得出了这个答案 def castfunction(msg:Any):Tuple2[Char,Int]={ msg match{case(x:Char,y:Int)=>Tuple2(x,y)} } 多谢各位。
弗兰克甜蜜而简单。。不熟悉这门语言。。所以我不知道这个特征。。工作完美。@DeeptiJain喜欢发现这种语言越来越甜:)
def function(msg: Any) = {
msg match {
case tuple @ (a: Any, b: Any) => tuple
}
}