Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 986
Stefan Avatar asked Apr 16 '10 09:04

Stefan


2 Answers

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.

like image 81
Sandor Murakozi Avatar answered Oct 05 '22 18:10

Sandor Murakozi


If you already have an object of type String it will never match a type PersonClass. It's actually a feature that the compiler does you not let do these matches that will never succeed.

With the Any type you are simply turning the type check off. It won't match with this definition but the compiler can't catch this problem.

like image 36
Thomas Jung Avatar answered Oct 05 '22 19:10

Thomas Jung