我创建了一个对象,用于演示如何使用case类:
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));
}
并且代码无法编译并提供错误
错误:' =>'预期,但'('发现
现在我改变了以下
case person : Person(firstName,lastName) => s" You gave me a Person Object with ${person.firstName} ${person.lastName}";
到
case person @ Person(firstName,lastName) => s" You gave me a Person Object with ${person.firstName} ${person.lastName}";
代码编译并成功运行。
现在我改变了
case str : String => s"you gave me a String ${str}";
到
case str @ String => s"you gave me a String ${str}";
它给我一个错误:
错误:对象java.lang.String不是值
的情况也是如此
case list : List(1,_*) // gives error
case list @ List(1,_*) // run successfully
所以我的问题是我应该在哪里使用 @ 而不是:
由于
答案 0 :(得分:4)
冒号用于匹配类型,@
用于通过右侧事物的unapply
方法执行递归模式匹配侧。
在您的示例中,String
是一种类型,但Person(x,y)
和List(1,_*)
不是。