main 函数
fun main(args: Array<String>) {
println("Hello, world!")
}
一切都有值
下面的输出 kotlin.Unit(println 本身没有返回值,所以返回 kotlin.Unit)
val isUnit = println("This is an expression")
println(isUnit)
创建函数
import java.util.* // required import
fun randomDay() : String {
val week = arrayOf ("Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday")
return week[Random().nextInt(week.size)]
}
fun fishFood (day : String) : String {
return when (day) {
"Monday" -> "flakes"
"Wednesday" -> "redworms"
"Thursday" -> "granules"
"Friday" -> "mosquitoes"
"Sunday" -> "plankton"
else -> "nothing"
}
}
fun feedTheFish() {
val day = randomDay()
val food = fishFood(day)
println ("Today is $day and the fish eat $food")
}
fun main(args: Array<String>) {
feedTheFish()
}
给函数参数添加默认值(有默认值的参数可以不传,没有的必传),
fun swim(speed: String = "fast") {
println("swimming $speed")
}
函数参数默认值不一定需要是值,也可以是函数调用
fun shouldChangeWater (day: String, temperature: Int = 22, dirty: Int = getDirtySensorReading()): Boolean {
}
单表达式的函数可以简写成
fun isTooHot(temperature: Int) = temperature > 30
过滤器
it 代表正在遍历元素
不满足条件的被过滤掉
val decorations = listOf ("rock", "pagoda", "plastic plant", "alligator", "flowerpot")
fun main() {
println( decorations.filter {it[0] == 'p'})
}
惰性过滤器
val filtered = decorations.asSequence().filter { it[0] == 'p' }
println("filtered: $filtered")
输出
filtered: kotlin.sequences.FilteringSequence@386cc1c4
val newList = filtered.toList()
println("new list: $newList")
才输出值
new list: [pagoda, plastic plant]
转换
val lazyMap = decorations.asSequence().map {
println("access: $it")
it
}
过滤+转换
val lazyMap2 = decorations.asSequence().filter {it[0] == 'p'}.map {
println("access: $it")
it
}
println("-----")
println("filtered: ${lazyMap2.toList()}")
lambda
var dirtyLevel = 20
val waterFilter = { dirty : Int -> dirty / 2}
println(waterFilter(dirtyLevel))
高阶函数
函数的参数是另一个函数
fun updateDirty(dirty: Int, operation: (Int) -> Int): Int {
return operation(dirty)
}
调用
val waterFilter: (Int) -> Int = { dirty -> dirty / 2 }
println(updateDirty(30, waterFilter))
传命名函数时
fun increaseDirty( start: Int ) = start + 1
println(updateDirty(15, ::increaseDirty))
如果最后一个参数是函数的话,有一个特殊写法
var dirtyLevel = 19;
dirtyLevel = updateDirty(dirtyLevel) { dirtyLevel -> dirtyLevel + 23}
println(dirtyLevel)
网友评论