About the Any type

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

Thank you

This must be 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.

Take a look at the docs here: Match Types | Scala 3 Language Reference | Scala Documentation


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

It’s undesirable to lose type information. People will say things like “use a typeclass” to operate differentially on inputs.

1 Like