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
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值