WIKOSO
WIKOSO

Reputation: 105

How to get the first Char from the first element of a list using kotlin?

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

Answers (2)

The Dude
The Dude

Reputation: 365

val myList = arrayOf( "myFirstElement", "mySecondElement")

myList[0].toCharArray()[0]

or

myList[0][0]

both worked for me

Upvotes: 0

Todd
Todd

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:

  1. We have an array (which I've renamed from myList to myArray to reduce confusion)
  2. We call the extension function called first() on Array, which gives us the first element of the Array, which is a String.
  3. We call the extension function called 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

Related Questions