Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property initialization without default value

I have a field that can be initialized in a secondary constructor, otherwise it will be initialized with the creation of a new object. I don’t want to use the default value as null or create an object that can be replaced by an object passed in the constructor.

my implementation:

class AggregationAdapter() {

    private var _libraryFilters: FiltersFromLibrary? = null
    private var libraryFilters: FiltersFromLibrary
    get() {
        if (_libraryFilters == null) _libraryFilters = FiltersFromLibrary()
        return _libraryFilters!!
    }
    set(value) {
        if (_libraryFilters == null) _libraryFilters = value
    }

    constructor(filtersFromLibrary: FiltersFromLibrary) : this() {
        libraryFilters = filtersFromLibrary
    }
}

So, I want to find out how good my way is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need a secondary constructor. You can use a default initializer
in the primary constructor. All your code above can be replaced with:

class AggregationAdapter(
    private val libraryFilters: FiltersFromLibrary = FiltersFromLibrary()
) {

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading