Search code examples
stringscalacastingany

Scala identify string with pattern matching


I wonder how to avoid casting Any to String but rather use pattern matching.

Having collected a dataframe from spark like df.select('column).first.toSeq.head Direct casting sort of is a workaround df.select('column).first.toSeq.head.asInstanceOf[String], but I would prefer to use scala native pattern matching like

val collectedFromSpark: Any = "someString"
  val realString:String = collectedFromSpark match{
    case s:String => _
    case _ => throw new Exception("expected something else")
  }

However, realString:String only receives Any and not String.

How can I formulate this cast in a scala native way?


Solution

  • Change your case to this:

    case s: String => s
    

    Now it will know that s is a String.