Kotlin初始化一个对象
我有一个基类,我正在扩展,但想膨胀一个普通的Java
构造函数将视图。
class TextView(context: Context?) : ViewAbstractClass(context)
我不知道如何在Kotlin
做到这一点。 Kotlin
有什么构造可以让你对对象进行复杂的初始化?
https://kotlinlang.org/docs/reference/classes.html#constructors
class Customer(name: String) { init { logger.info("Customer initialized with value ${name}") } }
有几个方法可以完成,但这是我一直在我的应用程序正在做的。
class TextView : ViewAbstractClass { constructor(context: Context) : super(context) constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) { // custom init code for this constructor. } constructor(context: Context, attributeSet: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attributeSet, defStyleAttr, defStyleRes) init { // Common init code } }
请注意,您实际上并没有在类签名中使用()
,而是明确地提供了所有的构造函数。
你可以在这里了解更多关于二级构造函数的信息: https : //kotlinlang.org/docs/reference/classes.html