lazy
定义为lazy的变量在第一次应用时才会求值
var a = 4, b = 2
lazy var c = a * b
Unit
相当于Java中的void
Nothing
函数抛出异常时返回Nothing
String
scala支持字符串插值
var name : String = "chenfeng"
var newstr : String = s"my name is ${name}"
3种函数:
def hello1(name : String) : String = {
s"new String return : {name}"
}
def hello3(x : Int, y : Int) = x + y // 只有一条语句可以省略代码块括号
3种for循环
val l = List("alice", "bob", "cathy")
for (
s <- l
) println(s)
for {
s <- l
if (s.length > 3)
} println(s)
val result_for = for {
s <- l
s1 = s.toUpperCase()
if (s1 != "")
} yield (s1)
println(result_for)
try and match
val result_try = try {
Integer.parseInt("dog")
} catch {
case _ => 0
} finally {
println("always be printed")
}
println(result_try)
val code = 3
val result_match = code match {
case 1 => "one"
case 2 => "two"
case _ => "others"
}
println(result_match)
2种求值策略
call by value
call by name
函数,高阶函数,匿名函数,递归函数
高阶函数:用函数作为形参或返回值的函数
def operate(f : (Int, Int) => Int) {
f(4, 4)
}
def greeting() = (name : String) => s"my name is ${name}"
匿名函数,又称为函数常量、函数文字量,格式为 (形参列表) => {函数体}
var add() = (x : Int, y : Int) => x + y
add(1, 2)
def greeting() = (name : String) => s"my name is ${name}"
greeting()("zhangsan")
def greeting2(x : Int) = (name : String) => s"my name ${x} is ${name}"
greeting(12)("olala")
递归函数:在函数式编程中实现循环的一种技术
尾递归函数:所有递归函数的调用都出现在函数的末尾,当编译器检测到是尾递归时,覆盖当前活动记录而不是在栈中创建新的
柯里化
object test {
def main(args: Array[String]): Unit = {
sum(x => x)(1)(5)
sum(x => x * x)(1)(5)
}
def sum(f: Int => Int)(a: Int)(b: Int): Int = {
@annotation.tailrec
def loop(n: Int, acc: Int): Int = {
if (n > b) {
println(s"n=${n}, acc=${acc}, innerest")
acc
} else {
println(s"n=${n}, acc=${acc}")
loop(n + 1, acc + f(n))
}
}
loop(a, 0)
}
}
List[T]
val l = List(1, 2, 3, 4)
连接元素
::,从后向前连接
val c = "x" :: "y" :: "z" :: Nil // List[String] = List(x, y, z)
连接列表
:::
val d = l ::: c // List[Any] = List(1, 2, 3, 4, x, y, z)
获取元素
l.head
l.tail
l.isEmpty
def walkthrough(list : List[Int]) : String= {
if (list.isEmpty)
""
else
l.head.toString + " " + walkthrough(list.tail)
}
walkthrough(l)
高级函数
toList
"this is a string".toList // List[Char] = List(t, h, i, s, , i, s, , a, , s, t, r, i, n, g)
filter
"this is a string, 123".toList.filter(x => Character.isDigit(x)) // 取出数字 List[Int] = List(1, 2, 3)
takeWhile
"this is a string, 123".toList.takeWhile(x => x != s) // List[String] = List(t, h, i, s, , i, s, , a, )
map 映射,将列表中元素一一映射到新的值
var a = "this is a string".toList
a.map(x => x.toUpperCase)
a.map(_.toUpperCase)
var b = List(1, 2, 3, 4, 5)
b.filter(x => x % 2 == 1)
b.filter(_ % 2 == 1).map(_ + 10)
var c = List(List(1, 2, 3), List(4, 5, 6))
c.map(x => x.filter(x % 2 == 1))
c.map(_.filter(_ % 2 == 1))
c.flatMap(_.filter(_%2==1)) // 将多层list压平成一层
规约,从左向右
reduceLeft
a.reduceLeft((x, y) => x + y)
a.reduceLeft(_+_)
foldLeft
a.foldLeft(0)((x, y) => x + y)
a.foldLeft(0)(_+_)
Range
1 to 10 // Range(1, 2, 3, ..., 10)
1 to 10 by 2 // Range(1, 3, 5, 7, 9)
1 until 10 // Range(1, 2, 3, ..., 9)
(1 to 10).toList // List[Int] = List(1, 2, 3, ..., 10)
Stream:Stream is a lazy list
val s = 1 #:: 2 #:: 3 #:: Steam.empty // Stream(1, ?)
val s = (1 until 1000000).toSteam // Stream(1, ?)
s.head // 1
s.tail // Stream(2, ?)
Map
val p = Map(1 -> "David", 9 -> "Elwood") // 创建
p(1) // 获取,String = David
p.contains(1) // true
p.keys // Set(1, 9)
p.values // MapLike(David, Elwood)
p + (8 -> "Archer")
p ++ List(3 -> "afa", 4 -> "fage")
p - 1
p -- List(1, 9, 3)
Tuple
创建
(1, 2)
1 -> 2
var a = List(1, 2, 3)
def sumSq(in : List[Int]) : (Int, Int, Int) = {
in.foldLeft((0, 0, 0))(t, v) => (t._1 + 1, t._2 + v, t._3 + v * v))
}
sumSq(a) // (3, 6, 14)
Scala快速排序
def QuickSort(nums : List[Int]) : List[Int] = { if (nums.length < 2) nums else QuickSort(nums.filter(_ < nums.head) ++ nums.filter(_ == nums.head) ++ qSort(nums.filter(_ > nums.head))