Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply list in Kotlin

Tags:

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?

like image 803
Nicole Foster Avatar asked Mar 24 '21 13:03

Nicole Foster


2 Answers

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
like image 100
Joffrey Avatar answered Oct 11 '22 17:10

Joffrey


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]
like image 26
Ben Shmuel Avatar answered Oct 11 '22 18:10

Ben Shmuel