0

I have tried to convert the existing the android code to Kotlin code. However, it showed the following error

enter image description here

The code before conversion.

 recyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                LayoutInflater layoutInflater = getLayoutInflater();
                return new RecyclerView.ViewHolder(layoutInflater.inflate(R.layout.item_restaurant2, parent, false)) {
                };
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            }

            @Override
            public int getItemCount() {
                return 3;
            }
        });

The code after conversion.

recyclerView!!.setAdapter(object : RecyclerView.Adapter() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
                val layoutInflater = layoutInflater
                return object : RecyclerView.ViewHolder(layoutInflater.inflate(R.layout.item_restaurant2, parent, false)) {

                }
            }

            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            }

            override fun getItemCount(): Int {
                return 3
            }
        })
Long Ranger
  • 5,888
  • 8
  • 43
  • 72
  • Is there a specific reason you want to use an anonymous adapter? – OneCricketeer Jan 07 '18 at 01:18
  • In fact, the error showed after I use the built in function(Convert Java to Kotlin File) in "Code -> Convert Java to Kotlin". I just want to know how to fix it. – Long Ranger Jan 08 '18 at 02:14
  • 1
    I'm talking about your Java code, before it was ever converted. It would make sense for you to actually make a class for the adapter, not in-line a `new Adapter()` into `setAdapater` – OneCricketeer Jan 08 '18 at 16:16
  • You are right. It would be make sense to make a class for it. I went to the wrong way in the beginning. – Long Ranger Jan 08 '18 at 23:48

1 Answers1

0

object : RecyclerView.Adapter() { - Kotlin really does not like Java's raw types when generics are involved. Specifying the ViewHolder type will probably fix your code.

For example, object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Kiskae
  • 24,655
  • 2
  • 77
  • 74
  • I am new to Kotlin syntax. Can you provide the answer of it ? – Long Ranger Jan 04 '18 at 02:49
  • After struggling 2 days, finally I understand what you mean. Now I use the statement recyclerView!!.adapter = object : RecyclerView.Adapter() and it works now. It seems I forgot it is the setter function for it. – Long Ranger Jan 08 '18 at 08:54