Reputation: 95
I have an array like this and I would like to loop through it and get the value "B". I know how to get it in Java but I have no idea how to get it in Kotlin. Could someone show me how to do this?
private val myArray = arrayOf({"A";"B"},{"C";"D"})
Thanks.
Upvotes: 7
Views: 20623
Reputation: 8096
{}
is not a valid operator to create array in kotlin you've to use arrayOf()
instead. In kotlin {}
is reserved for creating lambda funtions.
You could iterate over the array like this:
private val myArray = arrayOf(arrayOf("A", "B"),arrayOf("C", "D"))
for (innerArray in myArray) {
for(element in innerArray) {
println(element) // or your logic to catch the "B"
}
}
Upvotes: 5
Reputation: 1929
You can do it with just one Loop
val arr: Array<Array<String>> = arrayOf(arrayOf("A", "B"), arrayOf("C", "D"))
for (arr2: Array<String> in arr) {
val contains: Boolean = arr2.contains("B")
if (contains) {
println(arr2)
break
}
}
Upvotes: 1