Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classifier does not have a companion object, and thus must be initialized here

Tags:

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
        }
    }
}
like image 759
Farhana Naaz Ansari Avatar asked Nov 26 '18 06:11

Farhana Naaz Ansari


People also ask

Does not have a companion object and this must be initialized here?

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 ...

What is a Kotlin companion object?

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.

Can data class have companion object?

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.


1 Answers

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*/)
like image 109
Fred Avatar answered Sep 20 '22 06:09

Fred