scala模式匹配

match表达式

类似于Java switch语句

  • 能处理类型所有类型
  • 不需要break
  • 能够生成值
val firstArg=if(args.length>0) args(0) else ""
firstArg match{
    case "salt" => println("pepper")
    case "chips" => println("salsa")
    case "eggs" => println("bacon")
    case _ => println("huh?")	//以上未列出的值,使用“_”表示
}

样例类的模式匹配

模式匹配

  • 检查某个值(value)是否匹配某一个模式的机制,一个成功的匹配同时会将匹配值解构为其组成部分
//基本模式匹配
def matchTest(x: Int): String = x match {
  case 1 => "one"
  case 2 => "two"
  case _ => "many"
}
matchTest(3)  // many
matchTest(1)  // one
//模式守卫(在模式后面加上if 条件)
def matchTest2(x: Int): String = x match {
  case i if i==1 => "one"
  case i if i==2 => "two"
  case _ => "many"
}
matchTest2(3)  // many
matchTest2(1)  // one
//仅匹配类型
def matchTest3(x: Any): String = x match {
  case x:Int => "Int"
  case x:String => "String"
  case _ => "Any"
}
matchTest3(3.0)  // Any
matchTest3(1)     // Int
//仅匹配类型
def matchTest3(x: Any): String = x match {
  case x:Int => "Int"
  case x:String => "String"
  case _ => "Any"
}
matchTest3(3.0)  // Any
matchTest3(1)     // Int

非样例类的模式匹配

单例对象中指定unapply()方法时,称为提取器对象(Extractor Objects)
unapply()方法接受一个实例对象,返回最初创建它所用的参数

class Student(_name:String,_age:Int) {
  var name=_name
  var age=_age
}
object Student{
  def apply(name: String, age: Int): Student = new Student(name, age)
  def unapply(arg: Student): Option[(String, Int)] ={
    if(arg==null) None else Some(arg.name,arg.age)  
  }
}
def matchTest(x:Student)=x match {
    case Student(name,age) if age<=20 => println("young man")
    case Student(name,age) if age>20 => println("old man")
}
matchTest(Student("Jason",19))   //young man

偏函数

偏函数是只对函数定义域的一个子集进行定义的函数
PartialFunction[-A,+B]是一个特质

  • A为函数定义域,B为偏函数返回值类型
  • apply()
  • isDefindAt()
//自定义偏函数
val inc = new PartialFunction[Any, Int] {
    def apply(any: Any) = any.asInstanceOf[Int]+1
    def isDefinedAt(any: Any) = 
                                  if (any.isInstanceOf[Int]) true else false
}
List(1,2,3,"four").collect(inc)
val pf:PartialFunction[Any, Int]={case x:Int=>x+1} //返回一个偏函数
List(1,2,3,"four").collect(pf)  //输出List(2,3,4)

注解

Scala标准库注解包——scala.annotation
注解语法
可使用注解的地方

 

@注解名称(注解参数...)
常用注解
@throws、@deprecated、@unchecked、@SerialVersionUID……

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值