Writing a function that returns a MutableList

I have written this function to return a mutable list, however, something is wrong with the first line. When it is written as below I get the error “One type argument expected for interface MutableList”. I have also tried adding parentheses on the end of “MutableList” but this doesn’t resolve the problem. I am very new to programming in Kotlin, and my understanding of the first line here is that “getSeq” is the name of the function, that “n:Int” is the name of the variable that is passed into getSeq, and “MutableList” should be getSeq’s return type.
fun getSeq(n:Int): MutableList {
val r = mutableListOf(0)
while (r.size < 7)
if (r[r.size-1]+2>n)
r.add(r[r.size-1]-5)
else
r.add(r[r.size-1]+2)
return r
}

Right code is:

fun getSeq(n:Int): MutableList<Int> {
val r = mutableListOf(0)
while (r.size < 7)
if (r[r.size-1]+2>n)
r.add(r[r.size-1]-5)
else
r.add(r[r.size-1]+2)
return r
}

You could not return just MutableList, because it requires generic parameter - type of list value (in your case it is Int). So right return value is MutableList<Int>.

Please check details here: https://www.baeldung.com/kotlin-generics

1 Like