简体   繁体   English

将 kotlin 翻译成 Java

[英]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).我正在使用屏幕截图库(在 Github 中),它是用 Kotlin 编写的(我不太了解 Kotlin)。

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

I don't know how to translate to Java a part of code.我不知道如何将一部分代码翻译成 Java。 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 :以及如何将此代码转换为 Java :

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

The kotlin reference states thatkotlin 参考文献指出

it is used inside a lambda to refer to its parameter implicitly it在 lambda 中用于隐式引用其参数

So the code snippet says that onSuccess() has just one parameter which is called "it" inside the scope of onSuccess() .所以代码片段说onSuccess()只有一个参数,在onSuccess()的范围内称为“it”。 Similarly, onError() has just one parameter which is called "it" inside the scope of this function.类似地, onError()只有一个参数,在该函数的作用域内称为“it”。

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. lambdas 的问题在于,如果您还不知道相应的函数,那么您就完全不知道it究竟是什么。

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.如果我们假设在制作屏幕截图时将调用onSuccess()那么很可能在这种情况下it实际上可能是一个Screenshot对象。 Similarly, onError() should be called if something went wrong, so here it could be some kind of Exception .同样, onError()应该叫,如果出事了,所以在这里it可能是某种Exception

One way to find out is to look up ScreenshotResult in the library module.找出答案的一种方法是在库模块中查找ScreenshotResult

Here, we find the declaration of observe()在这里,我们找到了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现在我们知道,对于onSuccess()it是一个Screenshot而对于onError()it是一个Throwable

So if you implemented processScreenshot() , you would write a function which takes a Screenshot :因此,如果您实现了processScreenshot() ,您将编写一个获取Screenshot的函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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