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?
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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With