Search code examples
kotlin

Is there a way in Kotlin to provide code which whould always be executed *after* class contruction?


I have a class in Kotlin which I never want to be instantiated via the primary constructor. Both secondary constructors wind up initializing a property based on their parameters, and I want to be sure the property is initialized (which it won't be with the primary constructor).

I'd like to declare my property to be lateinit, and then test to ensure it was initialized before any class methods are executed (e.g. as a final step of construction), to generate some kind of meaningful error. I don't want to have to introduce guards into every class method.

Here's an example:

class ElementsContainer() {
    private lateinit var elements: Elements

    constructor(url: String): this() {
        val doc = Jsoup.connect(url).get()
        elements = doc.body().select("*")
    }

    constructor(newElements: Elements): this() {
        elements = newElements
    }
 ...
}

Is there a way for my class to validate that elements has been initialized as a final check at the end of construction (via this::elements.isInitialized), and fail construction if not (e.g. throw an exception)?


Solution

  • You can make the primary constructor private if you don't want it to be used:

    class ElementsContainer private constructor() {
        // ...
    }
    

    But if you always want elements to be available, you should make it mandatory for the primary constructor:

    class ElementsContainer(private val elements: Elements) {
        constructor(url: String) : this(Jsoup.connect(url).get().body().select("*"))
    }