Home > Back-end >  Property initialization without default value
Property initialization without default value

Time:04-06

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.

CodePudding user response:

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()
) {

}
  • Related