如何定义一个需要在Kotlin中延迟初始化的委托属性?

时间:2018-12-02 03:44:01

标签: kotlin

我需要通过委托类from datetime import datetime import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter df = <set_your_data_frame_here> myDates = pd.to_datetime(df['Month']) myValues = df['Energy_MWh'] fig, ax = plt.subplots() ax.plot(myDates,myValues) myFmt = DateFormatter("%b-%Y") ax.xaxis.set_major_formatter(myFmt) ## Rotate date labels automatically fig.autofmt_xdate() plt.show() 定义属性isBackgroundWindow,但是以下代码将导致NullPointerException错误。

我知道PreferenceTool中的private val prefs: SharedPreferences by lazy { }是惰性的,因此在系统调用PreferenceTool<T>时不会初始化对象 this ,这将导致空错误。

我希望使用代码PreferenceTool(this, getString(R.string.IsBackgroundName) , false),,但是 委托属性上不允许使用'lateinit'修饰符

我该怎么办?

主要

private lateinit var isBackgroundWindow: Boolean by PreferenceTool(this, getString(R.string.IsBackgroundName) , false)

代表课程

class UIHome : AppCompatActivity() {   

   //I think the object this is not initialized, it will cause null error.
    private var isBackgroundWindow: Boolean by PreferenceTool(this, getString(R.string.IsBackgroundName) , false) 

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_home)

        isBackgroundWindow=false
     }

}

1 个答案:

答案 0 :(得分:2)

您可以像这样延迟变量isBackground。您的UIHome类应为

 class UIHome : AppCompatActivity() {

 var isBackground: Boolean by Delegates.notNull<Boolean>()

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_uihome)
 isBackground = isBackgroundWindow()

}

fun isBackgroundWindow(): Boolean {
val isBackgroundWindow: Boolean by PreferenceTool(
    this, getString(R.string.IsBackgroundName), false
)
return isBackgroundWindow
}
}

这是避免空指针异常

isBackground?.let { 

  // your code
}