Nicole Foster
Nicole Foster

Reputation: 381

How to multiply list in Kotlin

If I have a list:

val a: mutableListOf<Int> = (1,2,3,4) and I want to have a new list b with (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)

In python, you could just have a * 3

How can this be achieved in Kotlin?

Upvotes: 9

Views: 5329

Answers (2)

Ben Shmuel
Ben Shmuel

Reputation: 1989

You can overload times operator in order to use a * 3

operator fun <T> MutableList<T>.times(increment: Int) {
    val len = this.size
    repeat(increment - 1) {
        this += this.subList(0, len)
    }
}

which is simple a+a+a like shown here Plus and minus operators

And now you can use it as * operator:

val a = mutableListOf(1, 2, 3, 4)
val b = mutableListOf("1", "2", "3", "4")
a * 3
b * 3
print(a)
print(b)

//output
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

also you might want to handle negative and zero cases, right now they won't change the List

val a = mutableListOf(1, 2, 3, 4)
val b = mutableListOf("1", "2", "3", "4")
a * -1
b * 0
print(a)
print(b)

[1, 2, 3, 4]
[1, 2, 3, 4]

Upvotes: 4

Joffrey
Joffrey

Reputation: 37720

First thing that comes to mind is creating a list of lists and flatten-ing it:

val count = 3
val a = listOf(1, 2, 3, 4)
val b = List(count) { a }.flatten()
println(b) // [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

From this you can write your own * operator:

operator fun <T> Iterable<T>.times(count: Int): List<T> = List(count) { this }.flatten()

And use it like in Python:

val a = listOf(1, 2, 3, 4)
val b = a * 3

Upvotes: 17

Related Questions