Skip to content

Instantly share code, notes, and snippets.

@thara
Last active December 6, 2018 14:23
Show Gist options
  • Select an option

  • Save thara/838f2ee3bcc166ff6bcea00860d38c49 to your computer and use it in GitHub Desktop.

Select an option

Save thara/838f2ee3bcc166ff6bcea00860d38c49 to your computer and use it in GitHub Desktop.
Kotlin isInitialized
class A {
lateinit var s: String
fun print() {
println(s)
}
}
fun main(args: Array<String>) {
A().print()
}
class B {
lateinit var s: String
fun print() {
if (::s.isInitialized) {
println(s)
}
}
}
fun main(args: Array<String>) {
B().print()
}
class C {
lateinit var s: String
fun print() {
if (s.isInitialized) { // この行でUnresolved referenceというコンパイルエラーが発生する
println(s)
}
}
}
fun main(args: Array<String>) {
C().print()
}
class D {
var s: String // コンパイルエラー: Property must be initialized
fun print() {
if (::s.isInitialized) { // コンパイルエラー: This declaration can only be called on a reference to a lateinit property
println(s)
}
}
}
fun main(args: Array<String>) {
D().print()
}
- if (::x.isInitialized) {
+ if (x.isInitialized) {
class X(val isInitialized: Boolean) {}
class Z {
lateinit var x: X
fun print() {
if (::x.isInitialized) {
print("Initialized")
} else {
print("Not initialized")
}
}
}
fun main(args: Array<String>) {
val z = Z()
z.x = X(false)
z.print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment