Reputation: 105
I want to get to the first Char from the first element of a list or an array example:
val myList = arrayOf(
"myFirstElement",
"mySecondElement")
i tried this : myList[0][0] and this myList[0].first() but it does not work
Upvotes: 1
Views: 2083
Reputation: 365
val myList = arrayOf( "myFirstElement", "mySecondElement")
myList[0].toCharArray()[0]
or
myList[0][0]
both worked for me
Upvotes: 0
Reputation: 31710
You can take advantage of a couple of extension functions that Kotlin provides to do this quite elegantly, assuming you know that the array will have at leastone item and it will have a first character:
myArray.first().first()
Breaking it down:
first()
on Array
, which gives us the first element of the Array, which is a String
.first()
on CharSequence
(which String
implements), which gives us the
first character of the String
.However: If you want to guard against the possibility that the array does not contain anything, you can use the Array.firstOrNull()
and CharSequence.firstOrNull()
extensions instead, along with the safe-traversal operator:
myArray.firstOrNull()?.firstOrNull()
Upvotes: 2