2

我有一个传递“任何”类型消息的 Scala 函数。在大多数情况下,它将是一个大小为 2 的元组。接收此消息的函数需要查看元组元素的具体类型:

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
    }
}
4

3 回答 3

9

你为什么不只使用模式匹配

def function(msg: Any) = {
  msg match {
    case tuple @ (a: Any, b: Any) => tuple
  }
}
于 2012-12-06T20:22:42.863 回答
0

模式匹配

msg match {
   case (x,y) =>  ...
}
于 2012-12-06T20:22:10.117 回答
0

在使用 Scala Build Tools 版本 sbt-0.13.8 进行测试后,我刚刚想出了这个答案

def castfunction(msg: Any):Tuple2[Char,Int] = { msg match { case (x: Char,y:Int) => Tuple2(x,y) } }

谢谢你。坦率

于 2015-05-15T01:08:25.927 回答