Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

How to display param's name correctly from Kotlin high order function in java

Here's a download function written by Kotlin, in order to know the download progress and statements like downloading or failed or success, I've created a callback named 'listener' with two parameters.

Kotlin :

object Downloader{
    fun download( url:String, listener:((progress:Int, status:Int )->Unit) ){
        //...
    }
}

Java :

Downloader.download( "TargetUrl" , new Function2<Integer, Integer, Unit>() {
       @Override
       public Unit invoke(Integer integer, Integer integer2) {
           //..
       }
});

As you can see in java code, we can't tell what's 'integer' and 'interger2' stand for. My question is how can I keep these names in java?

Expected Java code:

Downloader.download( "TargetUrl" , new Function2<Integer, Integer, Unit>() {
       @Override
       public Unit invoke(Integer progress, Integer status) {
           //..
       }
});

BIG THANKS !!!

question from:https://stackoverflow.com/questions/65841994/how-to-display-params-name-correctly-from-kotlin-high-order-function-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To let the caller know what those parameters mean you can consider:

  1. Document them properly.
  2. Create an interface as an alternative.
interface Listener {
  fun onChanged(progress: Int, status: Int)
}

object Downloader{
  fun download( url:String, listener: Listener) { ... }
}

You can than call it from Java (though the caller could still change those parameter names).

download("url", new Listener() {
  @Override
  public void onChanged(int progress, int status) {
    // ...      
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...