在Kotlin中,如果你不想在构造函数内部或类主体顶部初始化一个类属性,你基本上有以下两个选项(来自语言引用):

延迟初始化

lazy()是一个接受lambda并返回lazy <T>实例的函数,它可以作为实现lazy属性的委托:第一次调用get()执行传递给lazy()的lambda并记住结果,后续调用get()只返回记住的结果。 例子 公共类Hello { val myLazyString:通过lazy {"Hello"} }

第一个调用和随后的调用,不管它在哪里,对myLazyString都会返回Hello

晚些时候初始化

Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class. To handle this case, you can mark the property with the lateinit modifier: public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() } } The modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.

那么,既然这两种方法都能解决同一个问题,如何在这两种方法中正确选择呢?

我有一个Kotlin源文件,但我想把它翻译成Java。

如何将Kotlin转换为Java源代码?

我想从我的Android应用程序启动一个已安装的包。我认为使用意图是可能的,但我没有找到一种方法来做到这一点。有没有链接,在哪里可以找到相关信息?

我写了一个Android应用程序。现在,我想让设备在某个动作发生时震动。我该怎么做呢?

当试图通过IntelliJ运行示例CorDapp (GitHub CorDapp)时,我收到以下错误:

不能将使用JVM目标1.8构建的字节码内联为当前的字节码 使用JVM目标1.6构建

如何修改IntelliJ设置,使所有字节码都使用相同的JVM目标构建?

在Kotlin中,与这个表达式等价的是什么?

a ? b : c

这在Kotlin中是无效的代码。

我想知道是否有方法检查lateinit变量是否已初始化。例如:

class Foo() {

    private lateinit var myFile: File

    fun bar(path: String?) {
        path?.let { myFile = File(it) }
    }

    fun bar2() {
        myFile.whateverMethod()
        // May crash since I don't know whether myFile has been initialized
    }
}

我正在开发一个应用程序,每次运行它时,我都会收到这样的消息:

不幸的是,MyApp已停止。

我可以做什么来解决这个问题?


关于这个问题-显然是受什么是堆栈跟踪以及如何使用它调试应用程序错误的启发?,有很多问题表明他们的应用程序已经崩溃,没有任何进一步的细节。这个问题旨在指导Android新手程序员如何自己解决问题,或者提出正确的问题。

在Kotlin中没有静态关键字。

在Kotlin中表示静态Java方法的最佳方法是什么?

我正在更改keyListener上的EditText的值。

但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。

如何将光标移动到EditText文本的末尾。