简体   繁体   中英

Object in ViewHolder getter/setter required on Kotlin

not sure what is going on. This worked fine in Java but when switching to Kotlin I don't really know how to make this work. I get this error But I get the same error which is

Property getter or setter required on the val mMoment: Moment

class SquareViewHolder(v: CardView, viewModel: BarreViewModel) : RecyclerView.ViewHolder (v) {

    val mImage: ImageView
    val by lazy mMoment: Moment


    init {

        mImage = v.findViewById(R.id.square_moment)

        mImage.setOnClickListener {
            //val focused = ArrayList<Moment>(0)
            //focused.add(mMoment)

            //viewModel.focusedMoments = focused
            //viewModel.setItemClicked(true)
        }
    }



    fun bind(moment: Moment) {
        val mMoment = moment
    }
}

I have also tried var lateinit mMoment: Moment But I receive the same error.

Now, the moment object is a Kotlin Data Object, I'm not sure if that would cause a problem.

This worked on java, but for some reason kotlin doesn't seem to like the instantiation of the object this way. I don't know why. Thanks for any help!

In Java it was:

public class SquareMomentViewHolder extends RecyclerView.ViewHolder {

public ImageView mImage;
public Moment mMoment;

BarreChatViewModel viewModel;

public SquareMomentViewHolder(CardView v, BarreChatViewModel viewModel) {
    super(v);
    mImage = v.findViewById(R.id.square_moment);

    mImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            List<Moment> focused = new ArrayList(0);
            focused.add(mMoment);
            viewModel.setFocusedMoments(focused);

            viewModel.setItemClicked(true);
        }
    });
}

public void bind(Moment moment) {
    mMoment = moment;
}

}

A possible cause of this error might be that this dataclass is used for my ROOMDatabase. It's an entity object I was dragging to the User Interface. Maybe this isn't a proper way to do things. I don't know.

Lazy is where it will initialise the variable only when it is used, but it requires some code when declaring it as lazy.

Eg val mMoment by lazy { // Some code that generates this }

As your variable will be initialised in a bind, you should do:

lateinit var mMoment: Moment

This means that it will get initialised later on. If you try to use it without it being initialised, your program will throw an exception.

Or if this will potentially never get bound, you should initialise it as a nullable value:

var mMoment: Moment? = null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM