I have some parameter in the constructor. I need to convert it to something else and give it to the parent constructor. But the problem is that I want to remember the result of the conversion (which I give to the parent constructor) and I don't need to store it in the base class. How initialize value in the parent constructor argument? Like "val" in base constructor?
protected open class BindingViewHolder(binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root)
protected open class ModelViewHolder<Model : Identifiable<*>?, Binding : ViewDataBinding>(
parent: ViewGroup,
inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> Binding
) : BindingViewHolder(parent.inflateChildBinding(inflateBinding)) {
//some code
}
I have one problem in this code. I cant "val" "parent.inflateChildBinding(inflateBinding)"
CodePudding user response:
You can store the result that you want to remember in a SharedPreference
and retrieve it in the other class.
Storing data in SharedPreference
val sharedPref = context?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt(getString(R.string.converted_value), convertedValue)
apply()
}
Retrieving data from SharedPreference
val sharedPref = context?.getPreferences(Context.MODE_PRIVATE)
I don't fully understand your question. If your goal is to get the value from the previous class, just pass them to the new class's constructor.
Read more on SharedPreference
here
CodePudding user response:
In this case, you might as well make the binding
a property in the first class. You also need to use the exact type of binding depending on the case, so you should apply generics like this:
protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)
At this point, your second class can be merged into the first class ad a secondary constructor so we can avoid overuse of inheritance:
protected open class BindingViewHolder<T: ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root) {
constructor(
parent: ViewGroup,
inflateBinding: (LayoutInflater, ViewGroup, Boolean) -> T
): this(parent.inflateChildBinding(inflateBinding))
}
If desired, you can make the primary constructor private. The property in it will still be public.
To answer your literal question, you would make a primary constructor with the parameter you want to keep as a property and then make a secondary constructor with the parameters you need. It would basically look like my example above but with your second class, and the primary constructor only passing the binding
to the superconsttuctor.