scala – pattern match with typed pattern

def generalSize(x: Any) = x match { case s: String => s.length case m: Map[_, _] => m.size case _ => -1 }

The generalSize method returns the size or length of objects of various types. ItsargumentisoftypeAny,soitcouldbeanyvalue. Iftheargumentis a String,themethodreturnsthestring’slength. Thepattern“s: String”is a typed pattern; it matches every (non-null) instance of String. The pattern variable s then refers to that string.

Note that, even though s and x refer to the same value, the type of x is Any, but the type of s is String. So you can write s.length in the alternativeexpressionthatcorrespondstothepattern,butyoucouldnotwrite x.length, because the type Any does not have a length member.

Leave a comment