Object
Object content is static
If it is the same as the class name, it becomes a companion object
There is no static keyword in Scala
Inherit App, you can omit the main method
Apply method
Apply method can only be created in object
class Student(var name : String)
object Student {
def apply(name : String) = {
println("调用了apply方法")
new Student(name)
}
def main(args : Array[String]) : Unit = {
var student = Student("Freedom")
println(student.name)
}
}
Higher order function
(1)map
Equivalent to a loop, operate on each element in a collection (receive a function), return a new collection
var list = List(1,2,3)
list.map((i : Int) => i * 2)
list.map(_*2)
(2)foreach
foreach has no return value
(3)filter
Filter, select the data that meets, the parameter requires a function that returns a boolean value, filter out all the data that is true
var list = List(1,2,3)
list.filter((i : Int) => i % 2 == 0)
list.filter(_%2 == 0)
(4)zip
Merge two sets
List(1,2,3,).zip(List(4,5,6))
List(1,2,3).zip(List(4,5))
(5)partition
Partition based on the result of an assertion (that is, a certain condition, anonymous function)
var list = List(1,2,3)
list.partition((i : Int) => i % 2 == 0)
list.partition(_%2 == 0)
(6)find
Find the first element that meets the condition
var list = List(1,2,3)
list.find((i : Int) => i % 2 == 0)
list.find(_%2 == 0)
(7)flatten
Find the first element that meets the condition
List(List(1,2,3),List(4,5,6)).flatten
(8)flatmap
Equivalent to a map + flatten
var list = List(List(1,2,3),List(4,5,6))
list.flatmap(i => i.map(_*2))
Closures (nesting of functions)
In a function, contains the definition of another function, you can access the variables of the external function in the internal function
def out(factor: Double) = {
(x : Double) => x * factor
}
var triple = out(3)
triple(10)
out(3)(10)
Currying
Convert a function with multiple parameters into a function chain, each node is a single function
def add(x: Int,y : Int) = x + y //原始
def add(x : Int) = (y : Int) => x + y //闭包
def add(x : Int)(y : Int) = x + y