Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin initializing an object

I have a base class that I am extending, but want to inflate a view where the normal Java constructor would be.

class TextView(context: Context?) : ViewAbstractClass(context) 

I am not sure how to do this in Kotlin. What are the constructs are there Kotlin that allow you to do complex initialisation of objects?

like image 737
fergdev Avatar asked Nov 23 '25 21:11

fergdev


2 Answers

https://kotlinlang.org/docs/reference/classes.html#constructors

class Customer(name: String) {
    init {
        logger.info("Customer initialized with value ${name}")
    }
}
like image 135
voddan Avatar answered Nov 26 '25 10:11

voddan


There are a couple ways this can be done, however this is what I've been doing in my app.

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
    }

}

Notice that you don't actually use () in the class signature, but instead provide all the constructors explicitly.

You can learn more about secondary constructors here: https://kotlinlang.org/docs/reference/classes.html

like image 42
bclymer Avatar answered Nov 26 '25 09:11

bclymer