如何检查一个“lateinit”变量是否已经被初始化?

我想知道是否有办法检查一个lateinit变量是否已经初始化。

 import javafx.application.Application import javafx.event.EventHandler import javafx.geometry.Insets import javafx.geometry.Pos import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.control.ComboBox import javafx.scene.layout.VBox import javafx.stage.DirectoryChooser import javafx.stage.Stage import java.io.File class SeriesManager() { lateinit var seriesDir: File val allSeries by lazy { seriesDir.listFiles().map { it.name }.toTypedArray() } } class SeriesManagerUI : Application() { override fun start(primaryStage: Stage) { val sm = SeriesManager() val setSeriesDirBtn = Button("Change all series location").apply { onAction = EventHandler { sm.seriesDir = DirectoryChooser().apply { title = "Choose all series location" }.showDialog(primaryStage) } } val allSeriesList = ComboBox<String>().apply { promptText = "Select a series from here" isDisable = // I want this to be always true, unless the SeriesManager.seriesDir has been initialized } val setCurrentEpisodeBtn = Button("Change the current episode") val openNextEpisode = Button("Watch the next episode") val layout = VBox( setSeriesDirBtn, allSeriesList, setCurrentEpisodeBtn, openNextEpisode ).apply { padding = Insets(15.0) spacing = 10.0 alignment = Pos.CENTER } primaryStage.apply { scene = Scene(layout).apply { minWidth = 300.0 isResizable = false } title = "Series Manager" }.show() } } fun main(args: Array<String>) { Application.launch(SeriesManagerUI::class.java, *args) } 

尝试使用它,如果未初始化,您将收到UninitializedPropertyAccessException

lateinit特别适用于在施工之后,但在实际使用之前(大多数注入框架使用的模型)初始化字段的情况。 如果这不是你的用例lateinit可能不是正确的选择。

编辑:基于你想要做这样的事情会更好地工作:

 val chosenFile = SimpleObjectProperty<File?> val button: Button // Disables the button if chosenFile.get() is null button.disableProperty.bind(chosenFile.isNull()) 

Kotlin 1.2有一个lateinit改进,它允许直接检查lateinit变量的初始化状态:

 lateinit var file: File if (::file.isInitialized) { ... } 

请参阅JetBrains博客或KEEP提案上的通告。