今天的内容是lambda表达式,嗯,一个新鲜玩意儿
首先我们打开REPL定义一个无名函数
{println("hello")}()
lambda总是放在{}内
我们也可以这样使用
val swim = {println("swim")}
swim()
lambda也可以像有名字的函数一样有参数和返回值:
var dirty = 20
val waterFilter = {dirty:Int->dirty/2}
waterFilter(dirty)
也可以这样写
val waterFilter:(Int)->Int = {dirty->dirty/2}
还可以这样:
fun feedFish(dirty:Int) = dirty+10
fun updateDirty(dirty: Int,operation:(Int)->Int):Int{
return operation(dirty)
}
把上面的结合一下,总结一下lambda的用法:
var dirty = 20
val waterFilter:(Int)->Int = {dirty->dirty/2}
fun feedFish(dirty:Int) = dirty+10
fun updateDirty(dirty: Int,operation:(Int)->Int):Int{
return operation(dirty)
}
fun dirtyProcesser(){
dirty = updateDirty(dirty,waterFilter)
dirty = updateDirty(dirty,::feedFish)
dirty = updateDirty(dirty){
dirty->dirty+50
}
dirty = updateDirty(dirty,{
dirty->dirty+50
})
}
同时,repeat()函数就是将一个lambda重复许多次
lambda只是一种写法,熟悉了就好了
接下来是练习:
第一个选择做错了,留个纪念
问题是:
val random1 = random()
val random2 = {random()}
有什么不同
答案是:
第二个选项每次都会生成一个随机数并且random2是可以访问的
答案是:
random1 has a value assigned at compile time, and the value never changes when the variable is accessed.
random2 has a lambda assigned at compile time, and the lambda is executed every time the variable is referenced, returning a different value.
第二题:
Create a lambda and assign it to rollDice, which returns a dice roll (number between 1 and 12).
Extend the lambda to take an argument indicating the number of sides of the dice used for the roll.
If you haven't done so, fix the lambda to return 0 if the number of sides passed in is 0.
Create a new variable, rollDice2, for this same lambda using the function type notation.
为了省时间,直接看答案了:
val rollDice = { Random().nextInt(12) + 1}
val rollDice = { sides: Int ->
Random().nextInt(sides) + 1
}
val rollDice0 = { sides: Int ->
if (sides == 0) 0
else Random().nextInt(sides) + 1
}
val rollDice2: (Int) -> Int = { sides ->
if (sides == 0) 0
else Random().nextInt(sides) + 1
}
还有一道扩展:
Why would you want to use the function type notation instead of just the lambda?
Create a function gamePlay() that takes a roll of the dice as an argument and prints it out.
Pass your rollDice2 function as an argument to gamePlay() to generate a dice roll every time gamePlay() is called.
答案是:
Function type notation is more readable, which reduces errors, clearly showing the what type is passed in and what type is returned.
gamePlay(rollDice2(4))
fun gamePlay(diceRoll: Int){
// do something with the dice roll
println(diceRoll)
}