-
匿名函数内筛选 var len = "Harry Potter".count()
println(len)
var length = "Harry Potter".count() {
it == 'r'
}
println(length)
-
函数的定义与实现和调用 val methodAction: () -> String
methodAction = {
val input = 999999
"$input Derry"
}
println(methodAction())
-
函数的定义与实现
val methodAction2: (Int, Int, Int) -> String = {
number1, number2, number3 ->
val inputValue = 9999
"$inputValue params: $number1, $number2, $number3"
}
println(methodAction2(2, 3, 5))
-
it关键字, 如果定义的函数只有一个参数,如果没有指定参数名,那么系统回自动给参数命名为it val methodAction3 : (String) -> String = {"$it Derry"}
println(methodAction3("dddd"))
-
类型推断
val method1 = {
v1: Double, v2: Float, v3: Int ->
"v1:$v1, v2:$v2, v3:$v3"
}
println(method1(253.3, 342.3f, 23))
-
函数作为函数的参数 fun main(args: Array<String>) {
loginAPI("zhansna", "123456", responseResult = {
msg: String, code: Int ->
println(msg)
println(code)
})
loginAPI("zhansna", "123456"){ msg: String, code: Int ->
println(msg)
println(code)
}
}
fun loginAPI(username: String, userpwd: String, responseResult:(String, Int)-> Unit) {
if (webServiceLoginAPI(username, userpwd)) {
responseResult("login success", 200)
} else {
responseResult("login fail", 401)
}
}
fun webServiceLoginAPI(username: String, userpwd: String): Boolean {
return true
}
-
另一种写法,inline关键字,提高效率。用于函数参数是函数的函数
fun main(args: Array<String>) {
loginAPI("xdfs", "1223", ::responseResult)
}
fun responseResult(msg: String, code: Int) {
println("msg: $msg, code: $code")
}
inline fun loginAPI(username: String, userpwd: String, responseResult:(String, Int)-> Unit) {
if (webServiceLoginAPI(username, userpwd)) {
responseResult("login success", 200)
} else {
responseResult("login fail", 401)
}
}
fun webServiceLoginAPI(username: String, userpwd: String): Boolean {
return true
}
fun main(args: Array<String>) {
val show = show("zhangsan")
println(show("nihao", 20))
}
fun show(info: String): (String, Int) -> String {
return {
name: String, age: Int ->
"i'm anonymous "
}
}
|