Scala identify string with pattern matching

1.3k views Asked by At

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?

1

There are 1 answers

0
marstran On BEST ANSWER

Change your case to this:

case s: String => s

Now it will know that s is a String.