Scala:模式匹配,异常,case class,Option,偏函数,隐式转换

1、模式匹配

Scala中提供了更加强大的模式匹配match case,Scala的match case与Java的switch case最大的不同点在于,Java的switch case仅能匹配变量的值;而Scala的match case可以匹配各种情况,比如变量的类型、集合的元素、有值或无值等。

变量 match {
		case 值 => 代码
		case 值 => 代码
		case 值 => 代码
		....
		case _ => 代码
	}

单个字符串匹配

def test1(grade:String): Unit ={
  grade match {
    case "A" => println("Excellent...")
    case "B" => println("Good...")
    case "C" => println("Just so so...")
    case _ => println("You need to work harder...")
  }
}

test1("A")
test1("E")

结果:
Excellent...
You need to work harder...

带有if条件的模式匹配

def test2(name:String,grade:String): Unit ={
   
    grade match {
   
      case "A" => println("Excellent...")
      case "B" => println("Good....")
      case "C" => println("Just so so....")
      case _ if name == "haha" => println(name + ", you are a good boy, but ...")
      case _ => println("You need to work harder....")
    }
  }
  
test2("zhangsan","B")
test2("haha","F")
test2("lisi","x")
结果:
Good....
haha, you are a good boy, but ...
You need to work harder....

数组的模式匹配

def test3(arr: Array[String]) {
   
  arr match {
   
      //只有一个hadoop元素
    case Array("Hadoop") => println("Hi, Hadoop")
    // 2个任意的元素
    case Array(x, y) => println("Hi:" + x + " and " + y )
    // zhangsan开头的任意多个元素
    case Array("zhangsan", _*) => println("Hi, zhangsan and others")
    case _ => println("hey, who are you?")
  }
}

test3(Array("hadoop"))
test3(Array("haha","hehe"))
test3(Array("zhangsan","lisi","wangwu"))
结果:
hey, who are you?
Hi:haha and hehe
Hi, zhangsan and others

List模式匹配

def test4(list: List[String]): Unit = {
   
  list match 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值