repeat string n times in Kotlin

The built in CharSequence.repeat extension does this in an efficient way, see the source here. val str: String = “*”.repeat(100) Of course, this will still require O(n) steps to create the string. However, using this built-in stdlib function has its advantages: it’s cross-platform, easy to read, and can be improved in performance over time, if …

Read more

Kotlin sequence concatenation

Your code doesn’t copy the sequence elements, and sequenceOf(seq1, seq2).flatten() actually does what you want: it generates a sequence that takes items first from seq1 and then, when seq1 finishes, from seq2. Also, operator + is implemented in exactly this way, so you can just use it: (seq1 + seq2).forEach { … } The source …

Read more

Function definition: fun vs val

Kotlin is all about Java interoperability and defining a function as a val will produce a completely different result in terms of the interoperability. The following Kotlin class: class A { fun f(x: Int) = 42 val g = fun(x: Int) = 42 } is effectively equivalent to: public class A { private final Function1<Integer, …

Read more