variable binding to pattern in case clause in scala match expression

2.9k views Asked by At

I created an object for demonstrating use of use of case class as:

object MatchWithPattern extends App
{
    case class Person(firstName:String,lastName:String);
    def whatYouGaveMe(obj:Any):String={
                obj match {
                case str : String => s"you gave me a String ${str}";
                case person : Person(firstName,lastName) => s" You gave me a Person Object with ${person.firstName} ${person.lastName}";
                case default => "You gave me a Any class Object";
                }

        }

    var person= new Person("Mukesh", "Saini");
    Console.println(whatYouGaveMe(person));
} 

and code does not compile and gives the error

error: '=>' expected but '(' found

Now I change following

case person : Person(firstName,lastName) => s" You gave me a Person Object with ${person.firstName} ${person.lastName}";

to

case person @ Person(firstName,lastName) => s" You gave me a Person Object with ${person.firstName} ${person.lastName}";

code compiles and runs successfully.

Now I changes

case str : String => s"you gave me a String ${str}";

to

case str @ String => s"you gave me a String ${str}";

and it gives me an error as :

error: object java.lang.String is not a value

The same case is true for

case list : List(1,_*) // gives error

case list @ List(1,_*) // run successfully

So my question is that where should I use @ instead of :

Thanks

1

There are 1 answers

2
dhg On

The colon is used to match against the type, the @ is used to perform a recursive pattern match via the unapply method of the thing on the right-hand side.

In your examples, String is a type, but Person(x,y) and List(1,_*) are not.