Search code examples
kotlinrange

Convert ClosedRange<String> to List in Kotlin?


I wonder how I can convert the following ClosedRange<String> to List<String>:

 val letters: ClosedRange<String> = ("a".."z")

Solution

  • ClosedRange knows nothing about items in the middle. It is basically a start and an end item.

    The problem here is that you used strings and you should use chars. There is no meaningful answer on what strings exist between the string "a" and "z". What about: "hello"? Is it between them or not? But if we discuss chars, then obviously, we know what chars exist between 'a' and 'z', we can iterate over them or create a list:

    val letters = ('a'..'z').toList()
    

    Please be aware this code returns List<Char>, not List<String>. If you need strings, we can easily convert from chars:

    val letters = ('a'..'z').map { it.toString() }
    

    We don't need toList() anymore, because map implicitly converted from a range to a list.