简体   繁体   中英

translate kotlin to java

I'm using a screenshot library (in Github) and it is has been written in Kotlin(I don't know Kotlin very well).

<https://github.com/bolteu/screenshotty>

I don't know how to translate to Java a part of code. in the read me file :

val screenshotResult = screenshotManager.makeScreenshot()
val subscription = screenshotResult.observe(
   onSuccess = { processScreenshot(it) },
   onError = { onMakeScreenshotFailed(it) }
)

It says that you can get a screenshot object from "it"? how can I do that? please help me...

and how can I translate this code to Java :

fun show(screenshot: Screenshot) {
   val bitmap = when (screenshot) {
      is ScreenshotBitmap -> screenshot.bitmap
   }
   screenshotPreview.setImageBitmap(bitmap)
}

The kotlin reference states that

it is used inside a lambda to refer to its parameter implicitly

So the code snippet says that onSuccess() has just one parameter which is called "it" inside the scope of onSuccess() . Similarly, onError() has just one parameter which is called "it" inside the scope of this function.

The problem with lambdas is that if you don't know the corresponding function already then you're quite lost as to what it actually is.

If we assume that onSuccess() will be called if a screenshot was made then it is very likely that in this case it might actually be a Screenshot object. Similarly, onError() should be called if something went wrong, so here it could be some kind of Exception .

One way to find out is to look up ScreenshotResult in the library module.

Here, we find the declaration of observe()

fun observe(onSuccess: (Screenshot) -> Unit, onError: (Throwable) -> Unit): Subscription

Now we know that for onSuccess() , it will be a Screenshot whereas for onError() , it will be a Throwable

So if you implemented processScreenshot() , you would write a function which takes a Screenshot :

fun processScreenshot(screenshot: Screenshot){
    // your code here
}

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