case
package graphx import scala.util.Random object case01 { def main(args: Array[String]): Unit = { //TODO 简单匹配,值匹配: val booleans = List(true,false) for(bool <- booleans){ bool match{ case true=>println("heads") case false=>println("tails") case _=>println("no") } } val randomInt: Int = new Random().nextInt(10) randomInt match{ case 7=>println("luncky") case _=>println("unlucky") } //TODO 类型匹配 val sundries = List(23,"HELLO",8.5,'Q') for(sundry<-sundries){ sundry match { case i:Int=>println("got a Interger") case s:String=>println("got a String") case f:Double=>println("got a Double") case other=>println("got other thing") } } //TODO 根据顺序匹配 val willWork = List(1,3,23,90) val willNotWork = List(4, 18, 52) val empty = List() val lists = List(willWork,willNotWork,empty) println(lists.length) for(l<-lists){ l match{ case List(_,3,_,_)=>println("Four elements, with the 2nd being '3'") case List(_*)=>println("Any other list with 0 or more elements") } } //TODO 数组匹配 val tupA = ("Good", "Morning!") val tupB = ("Guten", "Tag!") val tuples = List(tupA,tupB) for(tup<-tuples){ tup match{ case(thingone,thingtwo) if thingone=="Good"=>println("A two-tuple starting with 'Good'") case(thingone,thingtwo)=>println("This has two things") } } //TODO 对象深度匹配 case class Person(name: String, age: Int) val alice = new Person("Alice", 25) val bob = new Person("Bob", 32) val charlie = new Person("Charlie", 32) val persons = List(alice,bob,charlie) for(person<-persons){ person match{ case Person("Alice", 25)=>println("hi Alice") case Person("Bob", 32) => println("Hi Bob!") case Person(name, age) =>println("Who are you") } } } }
posted on 2020-10-26 19:32 happygril3 阅读(155) 评论(0) 收藏 举报
浙公网安备 33010602011771号