1 字符串操作
1)多行
scala> val b =
| """
| |这是一个多行字符串
| |hello
| |lisi
| |hehe
| """.stripMargin
b: String =
"
这是一个多行字符串
hello
lisi
hehe
"
2)插值
scala> val name = "lisi"
name: String = lisi
scala> println(s"hello: $name")
hello: lisi
2 匿名函数
// 匿名函数
scala> def add = (x: Int, y: Int) => {
| x + y
| }
add: (Int, Int) => Int
// 匿名函数
scala> val f = (x: Int) => x + 1
f: Int => Int = <function1>
scala> add(1,3)
res1: Int = 4
scala> f(1)
res4: Int = 2
3 curry 柯里化
scala> def sum(a: Int, b: Int) = a + b
sum: (a: Int, b: Int)Int
scala> println(sum(2, 3))
5
// curry
scala> def sum2(a: Int)(b: Int) = a + b
sum2: (a: Int)(b: Int)Int
scala> println(sum2(2)(3))
5
4 高阶函数
1)map:逐个操作集合中的每个元素
scala> val l = List(1, 3, 4, 5, 6, 6, 7, 8)
l: List[Int] = List(1, 3, 4, 5, 6, 6, 7, 8)
scala> l.map(x => x + 1)
res7: List[Int] = List(2, 4, 5, 6, 7, 7, 8, 9)
scala> l.map(x => x * 2)
res8: List[Int] = List(2, 6, 8, 10, 12, 12, 14, 16)
scala> l.map(_ * 3)
res9: List[Int] = List(3, 9, 12, 15, 18, 18, 21, 24)
2)filter
scala> l.map(_ * 2).filter(_ > 8)
res10: List[Int] = List(10, 12, 12, 14, 16)
3)reduce
// 两两相加
scala> l.reduce(_ + _)
res11: Int = 40
// 两两相减
scala> l.reduceLeft(_ - _)
res12: Int = -38
// 从右往左两两相减 1-(3-(4-(5-(6-(7-8)))))
scala> l.reduceRight(_ - _)
res13: Int = -4
4)fold
0-1-3-4-5-6-6-7-8
scala> l.fold(0)(_ - _)
res14: Int = -40
5)flatten
scala> val L = List(List(1, 2), List(3, 4), List(5, 6))
L: List[List[Int]] = List(List(1, 2), List(3, 4), List(5, 6))
scala> L.flatten
res15: List[Int] = List(1, 2, 3, 4, 5, 6)
6)flatmap
scala> L.map(_.map(_ * 2))
res16: List[List[Int]] = List(List(2, 4), List(6, 8), List(10, 12))
scala> L.flatMap(_.map(_ * 2))
res17: List[Int] = List(2, 4, 6, 8, 10, 12)
scala> L.flatMap(x=>x)
res18: List[Int] = List(1, 2, 3, 4, 5, 6)
wordcount实现
val lines = List("hello tom hello jerry", "hello tom hello kitty hello china")
val wc = lines.flatMap(_.split(" ")).map((_, 1)).groupBy(_._1).map(t => (t._1, t._2.size)).toList.sortBy(_._2).reverse
val wc2 = lines.flatMap(_.split(" ")).map((_, 1)).groupBy(_._1).mapValues(_.size)
val wc3 = lines.flatMap(_.split(" ")).map((_, 1)).groupBy(_._1).mapValues(_.foldLeft(0)(_ + _._2))
5 偏函数
Scala 偏应用函数是一种表达式,你不需要提供函数需要的所有参数,只需要提供部分,或不提供所需参数。
def hello(name: String, message: String): Unit = {
println(s"hello, $name, $message")
}
val name = "lisi"
hello(name, "good day")
hello(name, "nice day")
println("=================")
// 偏函数:绑定name,_替换message,每次message不同
val helloWithName = hello(name, _: String)
helloWithName("good day")
helloWithName("nice day")
// 结果
hello, lisi, good day
hello, lisi, nice day
=================
hello, lisi, good day
hello, lisi, nice day