Using variables in super constructor


In my class constructor I want to pass variables to the super constructor, but I don’t see any way to do this in Kotlin.

For example, how would I accomplish this Java code in Kotlin?

class MyDbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 2;
    static final String DATABASE_NAME = "my.db";

    public MyDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);


In Kotlin classes have a primary constructor:

class MyDbHelper(context: Context) : SQLiteOpenHelper(context, "my.db", null, 2)

However, that also means that you have to pass the literal values of your fields to the super class sonstructor or define them outside of the class.


The values you pass are not variables, they are constants. In Kotlin you should define them in the companion object. When you do so (even using @JvmField or @JvmStatic), you can use these values in the constructor. That is also how the translator would translate your Java to Kotlin.


Thank you @medium and @pdvrieze