版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/85163466
1 Scala 函数高阶操作
- 字符串的高级操作
- 匿名函数
- curry函数
- 高阶函数
- 偏函数
2 字符串高级操作
- 多行
Interpolation
package com.scalatest.scala.advance
object StringApp extends App {
val s = "Hello: "
val name = "Mike"
println(s + name)
/*
* 插值操作
* */
println(s"Hello: $name")
val loc = "Beijing"
println(s"Hello: $name,welcome to $loc")
/*
* 先输入双引号,然后按住 shift,继续按双引号
* */
val ss =
"""
|多行字符串
|床前明月光
|疑是地上霜
""".stripMargin
println(ss)
}
3 匿名函数
匿名函数可以传给一个函数,也可以传给一个变量
4 curry
函数
package com.scalatest.scala.advance
/*
* 匿名函数:函数可以命名,也可以不命名
* */
object FunctionApp extends App{
def sum(a: Int, b: Int) = a + b
println(sum(1, 1))
def sum2(a: Int)(b: Int) = a + b
println(sum2(2)(3))
}
5 高阶函数
5.1 map
5.2 filter
5.3 take
5.4 reduce
5.5 flatmap
6 偏函数(用来模式匹配)
被包在花括号内没有 match 的一组 case 语句
package com.scalatest.scala.function
import scala.util.Random
object PartitalFunctionApp extends App {
val names = Array("Mike", "John", "Mary")
val name = names(Random.nextInt(names.length))
name match {
case "Mike" => println("Hello Mike")
case "Mary" => println("Hello Mary")
case _ => println("welcome....")
}
// A 输入类型,B 输出类型
def sayChinese: PartialFunction[String, String] = {
case "Mike" => "Hello Mike"
case "Mary" => "Hello Mary"
case _ => "welcome....."
}
println(sayChinese("Mike"))
}