'Casting Any to Tuple2
I have a Scala function which passes message of type 'Any'. In most cases it will be a tuple of size 2. The function that receives this message needs to see the specific types of the tuple elements:
main() {
// call to function
// msg is of type Any.
func (msg)
}
Now in my function,
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
}
}
Solution 1:[1]
Why don't you just use pattern matching?
def function(msg: Any) = {
msg match {
case tuple @ (a: Any, b: Any) => tuple
}
}
Solution 2:[2]
pattern matching
msg match {
case (x,y) => ...
}
Solution 3:[3]
I just came up with this answer after testing using Scala Build Tools version sbt-0.13.8
def castfunction(msg: Any):Tuple2[Char,Int] = {
msg match { case (x: Char,y:Int) => Tuple2(x,y) }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Didier Dupont |
Solution 3 | Ami Tavory |