I'm trying to convert a generic string to a number using scala
object h extends App {
def castTo[T](s: String): T = {
s.asInstanceOf[T]
}
print(castTo[Int]("20"))
print(castTo[Double]("20.1"))
}
the data:
name | value a | "1" b | "2.123" c | "abd"
the usecase: riight now I'm exporting the data to the user a method for each conversion. getNameAsDouble, getNameAsInteger and so forth. I wish to do getNameT to save lot's of code and make it a bit more pretty and easy to read the doc.
so, in case a programmer does :
getNameInt i want the program to print in this case: 1
getNameDouble i want the program to print in this case: 2.123
in cpp i could use dynamic_cast. there a way to do so in scala? ( i also tried to do so in java but couldn't find a way)
p.s. i've tried something like this, but i wandered if there is more generic way.
castTo[T] (s:String): T = {
...
case T instance of Integer => s.toInt
case T instance of Long => s.toLong
...
}
Stringinto a genericNumber, not to cast it. BTW, why do you want to do this?Stringalready provides thetoInt,toDouble& etc methods, why do you need to encapsulate all of them on a single method?