3

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?

2 Answers 2

2

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

class Customer(name: String) {
    init {
        logger.info("Customer initialized with value ${name}")
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How does the init code block relate to the standard constructors? Example ... can we set name after the init code block has run ... or can we call default constructors at the end of the init code block?
Think of the init block at the body of the default constructor. So you won't set name, you'll get name passed it.
2

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

5 Comments

this is a very peculiar piece of kotlin code. Not sure how it answers the Q
Is there a way to call super at different stages of initialisation? Like with the init mechanism ... can we call one of these other constructors at some stage during init? Or is init called after the default constructors have finished?
I just realized what he was actually asking. Crap. Yes, as voddan stated above, you're looking for init. init is always called after the parent's init and you do not need to call super (actually, you can not).
you can adjust the A to reflect the Q, or just delete it and make a fresh one
@bclymer off-topic: if the code above is in your app, something is very wrong with either kotlin or the app. In any way we (community or just me) may discuss that on the slack channel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.