scala> def test[A](s:A) = {
| s match {
| case i:Int => i.toFloat
| case s:String => s.size
| case _ => "zero"
| }
| }
def test[A](s: A): Any
the returned type is Any
how to convert Any type to a specified type?
scala> val x = test("world")
val x: Any = 5
scala> x > 1
^
error: value > is not a member of Any
scala> x.toInt
^
error: value toInt is not a member of Any
In scala you can “cast” to a specific known type using asInstanceOf[AType]. In general you shouldn’t need to (or want to) do this.
It’s usually better to encode your results into an ADT, or if you are using scala3, you could use a match type, which allows refining of an output type based on an input type.
Following the advice of @javax-swing it could look like this:
âžś scala
Welcome to Scala 3.1.0 (11.0.13, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala> type Elem[X] = X match
| case Int => Float
| case String => Int
| case X => String
|
scala> def test[X](x: X): Elem[X] = x match
| case x: Int => x.toFloat
| case x: String => x.size
| case x: X => "zero"
|
def test[X](x: X): Elem[X]
scala> test(5)
val res0: Float = 5.0
scala> test("abc")
val res1: Int = 3
scala> test(Nil)
val res2: String = zero