I have an Activity where an interface is declared and I have a ViewModel
class which has overridden interface and want to invoke the method of interface from Activity
to make changes in ViewModel
class but unable to call method in Activity
saying ViewModel class does not have a companion object, and thus must be initialized here. How to resolve this?
var selection: setSelectionSubRow? = null
selection=RowSubTShirtViewModel
selection!!.setNameSelection(false)
above code is in Activity
whose name is TShirtActivity
.
below code is from RowViewModel
class
class RowSubTShirtViewModel(private val subTShirtAdapter: SubTShirtAdapter, val context: TShirtActivity,
val tShirtBean: CommonItemBean, private val parentPosition: Int, private val position: Int) : BaseObservable() ,TShirtActivity.setSelectionSubRow{
fun getImageDrawable(): Drawable {
return if (tShirtBean.isSelected)
ContextCompat.getDrawable(context, R.drawable.green_border_circle)!!
else
ContextCompat.getDrawable(context, R.drawable.border_circle)!!
}
override fun setNameSelection(selection: Boolean) {
if (parentPosition == 6) {
if (position == 1) {
tShirtBean.isSelected = false
}
}
}
So when Kotlin complains and says Classifier Something does not have a companion object, and thus must be initialized here, it is basically telling you that that class does not have any static members (since it does not have a companion object), and so if you want to use it, either use it with parenthesis (initialize ...
Answer: Companion object is not a Singleton object or Pattern in Kotlin – It's primarily used to define class level variables and methods called static variables. This is common across all instances of the class.
Now it's possible for companion object. Note that the data class does not implement the interface, but its companion object does. 2- you can define extension functions on it. you can call these extension functions as functions on class name.
This line selection=RowSubTShirtViewModel
references the view model as if it were a named object, meaning you would have written instead of class object:
object RowSubTShirtViewModel {
//...
}
However, since that's not the case, kotlin is telling you that you cannot reference it like that and must initialize it. The constructor as quite a lot of parameters for me to guess what they are, but essentially you'd have to pass them in:
selection=RowSubTShirtViewModel(/*parameters here*/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With