Scala模式与case语句匹配
Scala支持内置模式匹配机制,这是更强大的功能之一。
模式匹配以关键字case开头。
每个都包含一个模式或者一个或者多个表达式,如果模式匹配,则应对其进行评估。
箭头符号=>将模式与表达式分开。
让我们考虑一个如何与整数值匹配的简单示例。
object Stud { def main(args:Array[String]) { println(studAgematch(7)) println(studAgematch(5)) println(studAgematch(12)) } def studAgematch(age:Int) : String = age match { case 5 => "Student Age is 5 " case 7 => "Student Age is 7" case 8 => "Student Age is 8" case 10 => "Student Age is 10" case _ => "Student age is greater than 10" } }
我们创建了对象Stud并定义了方法main,并通过传递Integer参数调用了studAgematch方法。
studAgematch方法接受一个Integer参数age,为age 5、7、8、10和其他数字定义各种大小写,并打印包含该大小写的语句。
我们正在传递数字7,5,12,因此将匹配这些数字的情况打印出来。
输入" Stud.main(null)"运行程序,您将在Scala shell中看到以下输出。
scala> Stud.main(null) Student Age is 7 Student Age is 5 Student age is greater than 10
在上面的示例中,我们看到了Integer数据类型的情况,但是也可以对字符串参数进行模式匹配。
让我们在下面看到一个例子。
object Student { def main(args: Array[String]) { println(matchAge("eight")) println(matchAge("twelve")) println(matchAge(7)) println(matchAge(9)) } def matchAge(age: Any): Any = age match { case 7 => "Age is Seven" case "eight" => 8 case y: Int => "Age is greater than 7" case _ => "Age is greater than 10" } }
我们使用main方法创建了Student对象,并通过传递带有字符串和整数数据类型的参数来调用matchAge方法。
在matchAge方法中,如果整数值为7,则满足第一种情况,如果整数值不是7,则满足y。
如果传递的参数的字符串值为"八",则执行具有字符串"八"的第二种情况。
",对于其他默认字符串值,执行case_。
通过键入Student.main(null)运行代码,您将看到以下输出。
scala> Student.main(null) 8 Age is greater than 10 Age is Seven Age is greater than 7
使用案例类进行模式匹配
Scala支持案例类,可用于案例表达式的模式匹配。
这些类是带有修饰符大小写的标准类。
让我们通过一个例子来理解这个概念。
object Stu { def main(args: Array[String]) { val st1 = new Student(1,"Adam", 12) val st2 = new Student(2,"John", 9) val st3 = new Student(3,"Reena", 16) for (st <- List(st1, st2, st3)) { st match { case Student(1,"Adam", 12) => println("Hello Adam") case Student(3,"Reena", 16) => println("Hello Reena") case Student(id,name, age) => println("Id: " + id + " Age: " + age + " Name: " + name) } } } case class Student(id:Int, name: String, age: Int) }
我们使用main方法创建一个对象Stu,并创建新的学生对象st1,st2和st3。
使用for循环使用对象st1,st2,st3和st4遍历列表,并通过传递值将Case表达式与Student构造函数一起使用。
在第一种情况下,匹配表达式是对象Adam,第二种是名称Reema,对于其他值,则按最后一种情况指定的方式打印详细信息。
指定学生构造函数的ID,名称和年龄参数为空。
通过键入Stu.main(null)
运行以上代码,您将看到以下输出。
scala> Stu.main(null) Hello Adam Id: 2 Age: 9 Name: John Hello Reena
关于案例类模式匹配的一些要点;
case关键字告诉编译器自动添加其他功能。
编译器自动将构造函数参数转换为不可变字段。
val关键字是可选的。
如果需要可变字段,则可以使用var关键字。
编译器使用指定为构造函数参数的字段实现equals,hashcode和toString方法。