在Kotlin中,如果不想在构造函数内部或类主体顶部初始化类属性,基本上有以下两个选项(来自语言引用):
lazy()
is a function that takes a lambda and returns an instance ofLazy<T>
which can serve as a delegate for implementing a lazy property: the first call toget()
executes the lambda passed tolazy()
and remembers the result, subsequent calls toget()
simply return the remembered result.Example个
public class Hello { val myLazyString: String by lazy { "Hello" } }
所以,第一次调用和后续调用,无论它在哪里,都会返回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.
要处理这种情况,可以使用lateinit修饰符标记属性:
public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() } }
修饰符只能用于在类的主体(而不是主构造函数)内声明的var属性,并且仅当该属性没有自定义getter或setter时才能使用.属性的类型必须为非null,并且不能是基元类型.
那么,既然这两个选项都能解决同一个问题,那么如何在这两个选项之间做出正确的 Select 呢?