首页 > 解决方案 > 如何初始化lateinit变量?

问题描述

我正在尝试运行我收到错误的开源应用程序

lateinit property textInput has not been initialized

textInput使用的主要代码

class MainActivity : BaseActivity() {

    private val drawerToggle by lazy { ActionBarDrawerToggle(this, drawer_layout, drawer_open, drawer_close) }

    private val survivalContent by lazy { SurvivalContent(assets) }

    private lateinit var currentUrl: String
    private lateinit var currentTopicName: String
    private lateinit var textInput: MutableList<String>


    private var lastFontSize = State.getFontSize()
    private var lastNightMode = State.nightModeString()
    private var lastAllowSelect = State.allowSelect()

    private val linearLayoutManager by lazy { LinearLayoutManager(this) }

    private var isInEditMode by observable(false, onChange = { _, _, newMode ->
        if (newMode) {
            fab.setImageResource(drawable.ic_image_remove_red_eye)
            contentRecycler.adapter = EditingRecyclerAdapter(textInput)
        } else {
            fab.setImageResource(drawable.ic_editor_mode_edit)
            contentRecycler.adapter = MarkdownRecyclerAdapter(textInput, imageWidth(), onURLClick)
        }

        contentRecycler.scrollToPosition(State.lastScrollPos)
    })

因为我是 android 开发的新手,所以在使用它之前我不知道如何初始化 lateinit 变量。在此之前,我尝试按照这个githubgit submodule update中提到的那样做,但它没有用。所以现在我希望问题出在初始化textInput变量。

标签: kotlinkotlin-lateinit

解决方案


您必须textInput在使用它之前初始化变量。为此,您可以执行以下操作:

textInput = mutableListOf("Abc", "Xyz")

来自文档:在初始化之前访问 lateinit 属性会引发一个特殊异常,该异常清楚地标识正在访问的属性以及它尚未初始化的事实。

阅读更多:https ://kotlinlang.org/docs/reference/properties.html#late-initialized-properties-and-variables


推荐阅读