Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Mutable List of Alphabets in Kotlin?

Tags:

kotlin

I want to create a MutableList of alphabets form A to Z but so far I can only think of the following method as the shortest one without writing each and every alphabet.

fun main()
{
    var alphabets: MutableList<Char> = mutableListOf()

    for (a in 'A'..'Z')
    {
        alphabets.add(a)
    }
    print(alphabets)
}

So I wanted to know if there is any Lambda implementation or shorter method for the same?

like image 931
EManual Avatar asked Aug 09 '20 11:08

EManual


People also ask

How do I create a list of strings in Kotlin?

Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.


1 Answers

You can use CharRange() or using .. operator to create a range.

For example:

val alphabets = ('A'..'Z').toMutableList()
print(alphabets)
// [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]

or

 val alphabets = CharRange('A','Z').toMutableList()
 print(alphabets)
 // [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]
like image 108
Ben Shmuel Avatar answered Nov 15 '22 08:11

Ben Shmuel