gpt4 book ai didi

scala - 将任何元素转换为元组2

转载 作者:行者123 更新时间:2023-12-01 10:24:48 25 4
gpt4 key购买 nike

我有一个Scala函数,可以传递“Any”类型的消息。在大多数情况下,它将是大小为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
}
}

最佳答案

您为什么不只使用pattern matching

def function(msg: Any) = {
msg match {
case tuple @ (a: Any, b: Any) => tuple
}
}

关于scala - 将任何元素转换为元组2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com