我们有时候在模式匹配的时候,多个case会输出同样结果,因此需要在一个case中写入多个情况,减少重复代码 scala模式匹配 defmatchTest(x:Int):String= xmatch{case1=>"one"case1.0=>"one"case_ =>"many"} 添加多条件 | defmatchTest(x:Int):String= xmatch{case1|1.0=>"one"case_ =>"many"}...
我们有时候在模式匹配的时候,多个case会输出同样结果,因此需要在一个case中写入多个情况,减少重复代码 scala模式匹配 defmatchTest(x:Int):String= xmatch{case1=>"one"case1.0=>"one"case_ =>"many"} 添加多条件 | defmatchTest(x:Int):String= xmatch{case1|1.0=>"one"case_ =>"many"}...
在匹配多个case类时,可以使用模式匹配来提取参数。 下面是一个示例代码,展示了如何在Scala中匹配多个case类并提取参数: 代码语言:txt 复制 case class Person(name: String, age: Int) case class Animal(name: String, species: String) def matchAndExtract(obj: Any): Unit = { obj match { case Pers...
$ scalac Test.scala $ scala Test manymatch 对应 Java 里的 switch,但是写在选择器表达式之后。即: 选择器 match {备选项}。 match 表达式通过以代码编写的先后次序尝试每个模式来完成计算,只要发现有一个匹配的case,剩下的case不会继续匹配。 接下来我们来看一个不同数据类型的模式匹配:...
package test_34 object test2 { def main(args: Array[String]): Unit = { //从数据库中获得数据 1,2,3,4 //要显示给用户的是 一等,二等,三等,四等 val level = 3 val levelTxt = level match { case 1 => …
在match表达式中使用Some,None,Option表达式 在match表达式式中使用Case class traitAnimalcaseclassDog(name:String)extendsAnimalcaseclassCat(name:String)extendsAnimalcaseobject WoodpeckerextendsAnimalobject CaseClassTestextendsApp{defdetermineType(x:Animal):String=x match{caseDog(moniker)=>"Got a Dog,name = ...
模式匹配是Scala中非常强大的一个特性,可以将数据进行解构,并选择性执行代码块。比如:在Scala中,通过变量后面接的match语句,与多个case进行匹配,如果匹配成功则执行相应的代码。这种特性与switch语句类似,但功能更为强大。例如:这段代码可以匹配不同的数值类型,并执行相应的动作,返回指定结果。与Java...
package test_34 object test1 { def main(args: Array[String]): Unit = { //身份证号 // val id = "421181200408088237" val id = "331181200408088237" //截取前两位 val pre = id.substring(0,2).toInt pre match { case 42 => println("湖北") case 11 => println("北京") case 31 => ...
变量match { case "常量1" => 表达式1 case "常量2" => 表达式2 case "常量3" => 表达式3 case _ => 表达式4 // 默认匹配 } 1. 2. 3. 4. 5. 6. 1.2 示例演示 需求说明 从控制台输入一个单词(使用StdIn.readLine方法) 判断该单词是否能够匹配以下单词,如果能匹配,返回一句话 ...
步骤2:定义 case 语句,包含多个模式 接下来,我们需要定义 case 语句,并包含多个模式。每个模式都可以匹配不同的值或类型。下面是一个示例: valuematch{case"option1"=>println("Option 1 selected")case"option2"=>println("Option 2 selected")case_=>println("Invalid option")} ...