如何使用lambda作为Kotlin中的回调

时间:2019-07-08 11:24:12

标签: kotlin

假设我有一个类似的课程:

class Testing() {
    var var1 = 0
    var str1 = ""
    var b = false

    fun test(var1: Int, str1: String, lambda1: (Boolean)->Unit){
    this.var1 = var1 
    this.str1 = str1 
    // do something
    }
}

如何调用方法 test 并传递 boolean 来运行lambda body?

var t1 = Testing()
t1.test(1, "String"){
      // do something else
}

2 个答案:

答案 0 :(得分:1)

您需要命名您的lambda参数,或者,如果不使用它,请将其命名为_

像这样:

fun example1() {
    var t1 = Testing()
    t1.test(1, "String") { bool ->
        // Do stuff
    }
}

fun example2() {
    var t1 = Testing()
    t1.test(1, "String", { bool -> 
        // Do stuff
    })
}

我假设您想在test类的Testing方法中调用回调。在这种情况下,您需要为函数提供参数,以便使用arg调用lambda。可以这样:

class Testing() {
    var var1 = 0
    var str1 = ""
    var b = false

    fun test(var1: Int, str1: String, lambdaArg: Boolean, lambda1: (Boolean)->Unit){
        this.var1 = var1
        this.str1 = str1
        // Invoke the callback
        lambda1(lambdaArg)
    }
}

或者,如果要传递给lambda的arg是test函数中发生的事情的函数,那么您可以省略向test提供lambda arg的功能,而改为 hardcode < / em>您的arg调用lambda,如下所示:

class Testing() {
    var var1 = 0
    var str1 = ""
    var b = false

    fun test(var1: Int, str1: String, lambda1: (Boolean)->Unit){
        this.var1 = var1
        this.str1 = str1
        if (this.var1 == 0) {
            lambda1(false)
        } else { 
            lambda1(true)
        }
    }
}

答案 1 :(得分:1)

class Testing() {
  var var1 = 0
  var str1 = ""
  var b = false

  fun test(var1: Int, str1: String, lambda1: (Boolean)->Unit){
    this.var1 = var1 
    this.str1 = str1 
    // do something
    lambda1(false) // or lambda1.invoke(true) // here your boolean value is passed to your lambda1-function
  }
}

其他地方:

test(1, "one") {
  // this is now your lambda1-function-body accepting a boolean...
  // here you now have three(+) ways to implement it...
}

lambda1-body的变体:

  1. 忽略给定的布尔值:

    test(1, "one") { // _ -> // <- you can write this out explicitly if you like
      println("boolean value is ignored here")
    }
    
  2. 使用it或命名参数(在本例中为passedBool):

    test(1, "one") { passedBool ->
      println("boolean value $passedBool was passed")
    }
    
  3. 方法参考:

    fun anythingThatConsumesABoolean(bool : Boolean) { }
    
    test(1, "one", ::anythingThatConsumesABoolean)
    

因此您可以看到:您不是从外部传递布尔值,而是在回调函数中处理它。