Home > Software engineering >  Kotlin implement abstract properties correctly
Kotlin implement abstract properties correctly

Time:11-12

For example java code

public abstract class BindingElement<T extends ViewDataBinding> {

    T binding;

    abstract public T createBinding(LayoutInflater inflater, ViewGroup parent);

    public BindingElement(ViewGroup parent) {
        binding = createBinding(LayoutInflater.from(parent.getContext()), parent);
        binding.setLifecycleOwner(ViewTreeLifecycleOwner.get(parent));
    }
}

I need some necessary property that defined in constructor. And then i will do something with that property. What is the best way write it in kotlin?

CodePudding user response:

Kotlin is no different from Java in case of abstractions, so I assume something like below will work

abstract class BindingElement<T: ViewDataBinding> {

    val binding: T

    abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T

    init {
        binding = createBinding(...)
    }
}

UPD: I noticed that your method requires field provided in constructor, so instead of init block you will use

constructor(parent: ViewGroup) {
    binding = createBinding(...)
}

CodePudding user response:

It may look more like Kotlin code

abstract class BindingElement<T: ViewDataBinding>(
    val parent: ViewGroup
) {
    val binding = createBinding(..., parent)

    abstract fun createBinding(LayoutInflater inflater, ViewGroup parent): T

}

And this code is calling the non-final function in the constructor which is an unsafe operation.

  • Related