模式匹配
1. 匹配值
变量 match {
case "" => 相关处理
case "" => 相关处理
case _ if(name == "") => 双重过滤相关处理
case _ => else相关处理
}
2. 匹配array
array match {
case Array("") => 相关处理
case Array(x,y) => 相关处理
case Array("",_*) => 相关处理
case _ => else相关处理
}
3. 匹配list
List match {
case ""::Nil => 相关处理
case x::y::Nil => 相关处理
case ""::tail => 相关处理
case _ => else相关处理
}
4. 匹配数据类型
obj match {
case i:Int => 相关处理
case s:String => 相关处理
case m:Map[_,_] => 相关处理
case _ => else相关处理
}
5. 匹配异常
try{}catch{
case e:exceptionname => println(相关处理)
case e:Exception => println(e.getMessage)
}finally{
//释放资源
}
6. 匹配case对象
//定义对象
calss Person
case class CTO(name:String,floor:String) extends Person
//匹配对象
def caseClassMatch(person Person):Unit = {
person match{
case CTO(name,floor) => name,floor值的相关处理 // 调用unapply根据对象提取值
case _ => else相关处理
}
}
7. 匹配option类型返回值
val v:Option[Int]=None
v match {
case some(1)=>println(v.get)
case None=>println("no value")
}
“_”,"_=","_*"的用法
- "_"的用法
1. 将函数赋值给一个变量:val 变量名= 函数名 _ 2. 匿名函数的参数x在=>右侧只出现一次,可以用_替代,例:(_:Int)+1**等效于:x:Int=>x+1** 匿名函数作为函数的参数时,参数类型可省略 例:一元函数:(1 to 3).map(_+1),二元函数:(1 to 3).sortWith(_>_) 3. 作为通配符,例:mport scala.math._ ,case _ => "many" 4. 元组(tuple)取值,例:(1,2,3)._2 5. 模式匹配获取元组(Tuple)的元素,当不需要某个值的时候可以使用_替代 例:val (first, second, _) = (2,3,4)
- "_="的用法
1. 类的成员变量的setter
- "_*"的用法
1. 调用函数时,变长参数使用Range打平的方式(start to end: _*)传入 例:def sum(args:Int*)=args.reduce(_+_),sum(start to end: _*) 2. 模式匹配获取数组(Array)的元素,当不需要后面多个值的时候可以使用_*替代 例:val Array(first, second, _*) = Array(1,2,3,4,5,6)
函数高级操作
- 字符串
插值:s"hello:$name,Welcome to $place" 多行字符串:idea中按住shift,连按三次“,回车 """ |多行字符串 |hello |world """.stripMargin
- currying函数
//将多个参数拆分到多个括号中 def 方法名(参数名1:参数类型)(参数名2:参数类型) = {函数体}
- 高阶函数
-
将函数作为参数传入函数
// 根据传入函数,递归求和 def sum(fun:Int =>Int,a:Int,b:int):Int{if(a>b)0 else f(a)+sum(f,a+1,b)} 例如: 加和:sum(x=>x,start,end) 平方和:sum(x=>x*x,start,end) 幂次和:sum(powerOfTwo,start,end) //powerOfTwo为幂次函数
-
1.map
// 逐个去操作集合中每个元素 l.map((参数名:参数类型) => 函数体) 简写: 一个参数: l.map(参数名=> 函数体) // _代表当前元素 l.map(_=> 函数体) l.map(_*2) 多个参数: l.map((参数名,参数名) => 函数体)
-
2.reduce
传递两个元素,到函数中,然后返回值与下一个元素,一起作为参数传入
- filter、flatten、flatmap、foreach
// 读文件 val txt = scala.io.Source.fromFile("path").mkString // 转list val txts = List(txt) // wordcount统计 val data = txts.flatMap(_split(",")).filter(_.length>4).map(x => (x,1)).reduce().take(10).foreach()
- 3.reduceLift、reduceRight、fold、foldLeft、foldRight
val list = List(1,2,3,4) list reduceLeft(_-_) // 从左到右规约 // 执行过程:((1-2)-3)-4 = -8 list reduceRight(_-_) 从右到左规约 // 执行过程:1-(2-(3-4)) = -2 list fold(0)(_-_) // 执行过程:0-1-2-3-4 = -10 list foldLeft(0)(_-_) 简写:(0 /: l)(_-_) // 执行过程:(((0-1)-2)-3)-4 = -10 list foldRight(0)(_-_) 简写:(0 :\ l)(_-_) // 执行过程:1-(2-(3-(4-0))) = -2
-