简体   繁体   中英

How to call Kotlin function with function as parameter in Java Code?

I have a kotlin method as follows:

fun methodWithCallBackAsParameter(callback:() -> Unit) {
    //Do Somejob
    callback()
}

In kotlin we simply use this method with following syntax:

methodWithCallBackAsParameter {
    //Some Instructions here.
}

Now I want to use this Kotlin method in a Java class but I am not able to figure out how.

只需在lambda表达式的末尾返回Unit.INSTANCE即可。

if you want to use lambda in android you have to change your app to use Java 1.8 instead of 1.7 use can do that by it from gradle

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

for more look this documentation https://developer.android.com/studio/write/java8-support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM