Initialize fields in Kotline


#1
private final int[] arrayList;
Context mContext;

    public AndroidImageAdapter(Context context, int[] arrayList) {
        this.mContext = context;
        this.arrayList = arrayList;
    }

I want To create constructor and define value and want to use it outside of constructor


#2

You posted some Java code. The equivalent in Kotlin would be this:

class AndroidImageAdapter(var mContext: Context, private val arrayList: Array<Int>)

#3

yes i already made constructor

class ItemAdapter constructor(context: Context, arrayList: ArrayList<String>) {

        val arrayList: ArrayList<String> = arrayList
        val context:Context = context 
    }

but i want to use arrayList and Context value outside of this constructor so what should i do for that


#4

The correct way to convert this code to Kotlin is what Jesper posted above. Both his code and your code (which is also correct but more verbose than necessary) allow you to use values outside of the constructor.


#5

but how can i use that in other method like i want to use par in my getView method


#6

By declaring context and arrayList as we’ve shown you, they are available in methods in your class. Is there something specific that you are having trouble with and that give you an error? If yes, then please show your code and explain what error message you get, then we can tell what’s wrong with it and how to fix it.


#7
 override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        mContext
        return p1!!
    }

giving Unresolved reference: mContext


#8

Since you did not name it mContext, you named the variable context


#9

Note here that there is no constructor body as such (only field initialisers). The block in curly braces is the class body, not the constructor body. As such val arrayList and val context are property declarations with implicit backing fields. The android convention of fields prefixed with m doesn’t work with Kotlin properties.