Slices in Kotlin
import kotlin.collections.slice
fun main() {
// In Kotlin, we use Lists instead of slices. Lists are typed only by
// the elements they contain. An uninitialized list is empty but not null.
var s: List<String> = listOf()
println("uninit: $s ${s.isEmpty()} ${s.size == 0}")
// To create an empty list with non-zero size, we can use MutableList
s = MutableList(3) { "" }
println("emp: $s len: ${s.size}")
// We can set and get just like with arrays
s[0] = "a"
s[1] = "b"
s[2] = "c"
println("set: $s")
println("get: ${s[2]}")
// size returns the length of the list as expected
println("len: ${s.size}")
// In Kotlin, we use the + operator or the mutableListOf function
// to add elements to a list
s = s + "d"
s = s + listOf("e", "f")
println("apd: $s")
// Lists can be copied using the toList() function
val c = s.toList()
println("cpy: $c")
// Kotlin supports list slicing with a similar syntax
val l = s.slice(2..4)
println("sl1: $l")
// This slices up to (but excluding) index 5
val l2 = s.slice(0 until 5)
println("sl2: $l2")
// And this slices from (and including) index 2 to the end
val l3 = s.slice(2 until s.size)
println("sl3: $l3")
// We can declare and initialize a list in a single line as well
val t = listOf("g", "h", "i")
println("dcl: $t")
// Kotlin has built-in list comparison
val t2 = listOf("g", "h", "i")
if (t == t2) {
println("t == t2")
}
// Lists can be composed into multi-dimensional data structures
val twoD = List(3) { i ->
List(i + 1) { j -> i + j }
}
println("2d: $twoD")
}
This Kotlin code demonstrates concepts similar to Go’s slices, using Kotlin’s List and MutableList types. Here are some key differences and explanations:
Kotlin uses
List
andMutableList
instead of slices.List
is immutable by default, whileMutableList
allows modifications.Kotlin lists are always initialized (empty if not explicitly populated), unlike Go slices which can be nil.
The
append
function in Go is replaced by the+
operator ormutableListOf
function in Kotlin.Kotlin uses
slice()
function for slicing, which is similar to Go’s slice syntax.Kotlin has built-in list comparison with
==
, unlike Go which requires a separate function.Multi-dimensional lists in Kotlin can be created using nested
List
constructors.
When you run this program, you’ll see output similar to the Go version, demonstrating the various list operations in Kotlin.
Kotlin’s collections, including List, provide a rich set of functions for manipulation and querying, making them powerful tools for data handling in Kotlin programs.