ArrayAdapter use Kotlin android

g71132 picture g71132 · Jan 29, 2017 · Viewed 25.1k times · Source

SoI'm learning kotlin and now I need to write an ArrayAdapter, but I've some error when trying to do this:

convertView = vi.inflate(resource, null) 

kotlin is telling me

Val cannot be reassigned

In the site kotline I convert java class to kotlin class and try to do like in this site. Why is there an error and how can I fix this? Here is the whole code.

open class MyAdapter(context: Context, resource: Int, list: ArrayList<MyItems>) :
        ArrayAdapter<MyItems>(context, resource, list) {

    var resource: Int
    var list: ArrayList<MyItems>
    var vi: LayoutInflater

    init {
        this.resource = resource
        this.list = list
        this.vi = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        var holder: ViewHolder

        if(convertView == null){
            convertView = vi.inflate(resource, null) //error in this line
            holder = ViewHolder()

            holder.image = convertView.findViewById(R.id.myImage) as ImageView?

            convertView.tag(holder) //error in this line

        } else {
            holder = convertView.tag as ViewHolder
        }

        return convertView
    }

    internal class ViewHolder {
        var image: ImageView? = null
    }

}

Answer

Kiskae picture Kiskae · Jan 29, 2017

Parameter variable cannot be re-assigned, you will need to create a local variable to hold your returned view:

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
    var holder: ViewHolder
    var retView: View

    if(convertView == null){
        retView = vi.inflate(resource, null)
        holder = ViewHolder()

        holder.image = retView.findViewById(R.id.myImage) as ImageView?

        retView.tag = holder

    } else {
        holder = convertView.tag as ViewHolder
        retView = convertView
    }

    return retView
}