Scala-Object对象、Apply方法、高阶函数

Object

Object对象中的内容都是静态的

如果和类名相同,则成为伴生对象

Scala中没有static关键字

继承App,可以省略main方法

Apply方法

Apply方法只能在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)
	}
}

高阶函数

(1)map

相当于一个循环,对某个集合中的每个元素都进行操作(接收一个函数),返回一个新的集合

var list = List(1,2,3)
list.map((i : Int) => i * 2)
list.map(_*2)

(2)foreach

foreach没有返回值

(3)filter

过滤,选择满足的数据,参数要求一个返回boolean值的函数,筛选出所有为true的数据

var list = List(1,2,3)
list.filter((i : Int) => i % 2 == 0)
list.filter(_%2 == 0)

(4)zip

合并两个集合

List(1,2,3,).zip(List(4,5,6))
List(1,2,3).zip(List(4,5))

(5)partition

根据断言(就是某个条件,匿名函数)的结果,来进行分区

var list = List(1,2,3)
list.partition((i : Int) => i % 2 == 0)
list.partition(_%2 == 0)

(6)find

查找第一个满足条件的元素

var list = List(1,2,3)
list.find((i : Int) => i % 2 == 0)
list.find(_%2 == 0)

(7)flatten

查找第一个满足条件的元素

List(List(1,2,3),List(4,5,6)).flatten

(8)flatmap

相当于一个map+flatten

var list = List(List(1,2,3),List(4,5,6))
list.flatmap(i => i.map(_*2))

闭包(函数的嵌套)

在一个函数的里面,包含了另一个函数的定义,可以在内函数中访问外函数的变量

def out(factor: Double) = {
	(x : Double) => x * factor
}
var triple = out(3)
triple(10)
out(3)(10)

柯里化

把具有多个参数的函数,转化为一个函数链,每个节点上都是单一函数

def add(x: Int,y : Int) = x + y   //原始
def add(x : Int) = (y : Int) => x + y  //闭包
def add(x : Int)(y : Int) = x + y
  
发布了131 篇原创文章 · 获赞 12 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/JavaDestiny/article/details/92750569