object PatternMatching { def main (args: Array[String]): Unit = { var a: Int = 10 var b: Int = 20 var operator: Char = '+' var result = operator match { case '+' => a + b case '-' => a- b case '*' => a * b case '/' => a / b case _ => "matching fail" } println(result) } }
object PatternType { def main (args: Array[String]): Unit = { println(decribeConst(true)) println(decribeType(List(2))) println(decribeType(List("hello"))) println(decribeType(Array(5))) println(decribeType(Array("hello"))) } /** * 匹配常量 */ def decribeConst (x: Any) = x match { case 1 => "int one" case "hello" => "string hello" case true => "boolean true" case '+' => "char" + ' ' case _ => "" } /** * 匹配类型 */ def decribeType(x:Any) =x match { case i:Int=>"Int" // 泛型擦除 List类型编译器会忽略泛型 case list:List[String]=>"list " case array:Array[Int]=>"Array[Int]" case a=>"something else" } }
// 匹配列表 // 方式一 for (list <- List( List(0),List(1, 0), List(0, 0, 0), List(1, 1, 0),List(88), List("hello") )) { val result = list match { case List(0) => "0" case List(x, y) => "List(x, y): " + x + ", " + y case List(0, _*) => "List(0, ...)" case List(a) => "List(a): " + a case _ => "something else" } println(result) } // 方式二 val list1 = List(1, 2, 5, 7, 24) val list = List(24) list match { case first :: second :: rest => println(s"first: $first, second: $second, rest: $rest") case _ => println("something else") } println("===========================")
def main (args: Array[String]): Unit = { for (arr <- List( Array(0), Array(1, 0), Array(0, 1, 0), Array(1, 1, 0), Array(2, 3, 7, 15), Array("hello", 1, 30) )) { val result = arr match { case Array(0) => s"0 => ${arr.mkString(",")}" case Array(1, 0) => s"Array(1, 0)=> ${arr.mkString(",")}" // 匹配两元素数组 case Array(x, y) => s"Array(x,y)=> ${arr.mkString(",")}" // _* 代表任意多个元素 case Array(0, _*) => s"以0开头的数组=> ${arr.mkString(",")}" case Array(x, 1, z) => s"中间为1的三元素数组=> ${arr.mkString(",")}" case _ => s"something else" } println(result) } }
for (tuple <- List( (0, 1), (0, 0), (0, 1, 0), (0, 1, 1), (1, 23, 56), ("hello", true, 0.5) )){ val result = tuple match { case (a, b) => "" + a + ", " + b case (0, _) => "(0, _)" case (a, 1, _) => "(a, 1, _) " + a case (x, y, z) => "(x, y, z) " + x + " " + y + " " + z case _ => "something else" } println(result)
/** * 匹配对象 */ object MathcObject { def main (args: Array[String]): Unit = { val student = new Student("alice", 19) // 针对对象实例的内容进行匹配 val result = student match { case Student("alice", 18) => "Alice, 18" case _ => "Else" } println(result) } // 定义类 class Student (val name: String, val age: Int) // 定义伴生对象 object Student { // apply 根据传入的值 构建一个对象 def apply (name: String, age: Int): Student = new Student(name, age) // unapply 根据传入的对象 ,还原属性值 用做模式匹配 def unapply (student: Student): Option[(String, Int)] = { if (student == null) { None } else { Some((student.name, student.age)) } } } }
说明:
使用case关键字简化开发
object Test05_MatchCaseClass { def main(args: Array[String]): Unit = { val student = Student1("alice", 18) // 针对对象实例的内容进行匹配 val result = student match { case Student1("alice", 18) => "Alice, 18" case _ => "Else" } println(result) } } // 定义样例类 case class Student1(name: String, age: Int)
def main(args: Array[String]): Unit = { def abs(x: Int) = x match { case i: Int if i >= 0 => i case j: Int if j < 0 => j case _ => "type illegal" } println(abs( 5))
object MatchVar { def main (args: Array[String]): Unit = { val (x,y)=(1,2) println(s"$x,$y")//1,2 val Array(first, second, _*) = Array(1, 7, 2, 9,4) println(s"first=$first,second=$second")// first=1,second=7 } }
class RichFile(val from:File){ def read=Source.fromFilr(from.getPath).mkString }
implicit def fire2RichFile(from:File)=new RichFile(from)
new File(“README”).read //File 中没有read方法 尝试匹配参数为File对象的隐式函数 尝试将Flie对象转为具有read方法的对象
sqrt(Fraction(1,4)) // sqrt预期的是一个Double 将调用fraction2Doubel
3* Fraction(4,5) // 将掉用int2Fraction 因为int的* 方法不接受Fraction作为参数
package chapter09plus object Test02_Implicit { def main(args: Array[String]): Unit = { // 正常调用 val new12 = new MyRichInt(12) println(new12.myMax(15)) // 1. 隐式函数 implicit def convert(num: Int): MyRichInt = new MyRichInt(num) // 如果整型没有 myMax的方法 编译器会在当前作用域内找implicit声明的函数 // 尝试将整数转为能调用myMax方法的对象 println(12.myMax(15)) println("============================") // 2. 隐式类: implicit class MyRichInt2(val self: Int) { //自定义比较大小的方法 def myMax2(n: Int): Int = if ( n < self ) self else n def myMin2(n: Int): Int = if ( n < self ) n else self } println(12.myMin2(15)) // 自定义类 class MyRichInt(val self: Int) { // 自定义比较大小的方法 def myMax(n: Int): Int = if ( n < self ) self else n def myMin(n: Int): Int = if ( n < self ) n else self }
// 3. 隐式参数 implicit val str: String = "alice" // implicit val str2: String = "alice2" implicit val num: Int = 18 // 如果不传 在当前作用域内会匹配implicit 定义的同类型的变量, def sayHello()(implicit name: String): Unit = { println("hello, " + name) } def sayHi(implicit name: String = "atguigu"): Unit = {// 优先匹配隐式参数 println("hi, " + name) } sayHello sayHi // 简便写法 def hiAge(): Unit = { println("hi, " + implicitly[Int]) } hiAge() } }
//在object当中定义隐式类。使用到前面的person3的参数 implicit class Person4(p: Person3) { def ShowName(): Unit = { println(p.name + " is ShowNaame") } } //在mian方法中调用 val p3 = new Person3("preson3_name") p3.ShowName()
class MyList [+T]{ 协变 } class MyList[-T]{ 逆变 } class MyList [T]{ 不变 }