Stefan Stefan -3 years ago 118
Scala Question

Scala wont pattern match with java.lang.String and Case Class

Hello fellow Scala Programmers

I have been working with Scala for some month now, however I have a problem with some properly basic stuff, I am hoping you will help my out with it.

case class PersonClass(name: String, age: Int)

object CaseTester {
def main(args:Array[String])
{
val string = "hej"
string match {
case e:String => println(string)
case PersonClass => println(string)
}
}
}


When I am doing like this I get error:

pattern type is incompatible with expected type;
found : object PersonClass
required: java.lang.String
case PersonClass => println(string)


And if I then change the second line in the pattern matching to the following:

case e:PersonClass => println(string)


I then get the error:

error: scrutinee is incompatible with pattern type;
found : PersonClass
required: java.lang.String
case e:PersonClass => println(string)


However if I change the string definition to the following it compiles fine in both cases.

val string:AnyRef = "hej"

Answer Source

The inferred type of string is String. That is known after the declaration of the val.

As we already know it during pattern matching it doesn't make sense to match patterns that are not Strings (like your PersonClass), as they will never match. That's what the "pattern type is incompatible with expected type; found : object PersonClass required: java.lang.String case PersonClass => println(string)" error means: we expect a pattern that is a subclass of String, but found something (PersonClass) which is not.

When you force the type AnyRef the situation changes. The compiler will treat string as Anyref, so patterns that extend AnyRef might match. PersonClass is AnyRef, so you don't get error.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download