First of all, you're using Java-style constructors. Kotlin constructors are denoted by the constructor
keyword, or by using primary constructors (parenthesis after the class name). fun ClassName
is not how constructors are declared in Kotlin.
The reason I'm pointing this out is because you won't be able to initialize your class properly if you don't have the constructors right.
You have two options: First is using secondary constructors:
constructor(resId: Int, theAnswer: Boolean) {
resultId = resId
answerT = theAnswer
}
The second is using primary:
class Question(var resId: Int, var theAnswer: Boolean) { // these might be val instead; change these if you don't change the vars. you can also remove the brackets if you don't have a class body.
}
Using var
or val
in primary constructors also declares them for the class. If you don't use var
or val
, they're only available in the init
block, or for variable initialization (until the initialization of the class is done, just like in constructors). You can compare using var
or val
to also adding this.someField = someField
, where as without it's just used in the constructor.
Also note that secondary constructors are required to call the primary constructor if one exists. You'll also need primary constructors for some classes that require passing specific fields that you can't initialize directly, whether it is because it requires a specific instance to work, or it's a singleton implementation of an abstract class or an interface.
As for the list, it depends on how you want to do it. Your Java code uses arrays, and not lists. For lists though, you use listOf(items)
, and for arrays, you can use arrayOf
. arrayOf()
works exactly like listOf
, except it returns Question[]
, and not a List<Question>
. The correct initialization of a list (or array) is like this:
val questions = listOf(Question(R.string.question_a, true), ...)
listOf
takes a vararg argument of items, so you can also create empty lists or arrays like that (Though for empty arrays, that's kinda pointless).
Types are automatically inferred too, so you don't need to explicitly type : List<Question>
, or listOf<Question>(...)
. You need to explicitly declare them if you don't pass any arguments.
There's also the option to manually add it if you feel like that. You can for an instance initialize lists directly and call .add
on those.