Is there a standard idiom for making a range of a ...
# codingconventions
Is there a standard idiom for making a range of a single value?
Copy code
inline fun Char.toRange(): CharRange =

fun `toRange creates a range with a single value`() {
    val range = 'Z'.toRange()
    assertEquals('Z', range.first)
    assertEquals('Z', range.last)
My primary complaint with
is that I have to specify the value twice. Making a
val Char.range: CharRange
would get me almost as short as the above, but it feels more appropriate for it to be a function
I don't think that there is any built-in stdlib function nor dedicated syntactic idiom for this - the use case sounds quite rare, so I'm not surprised. IMO your
extension is as good as you can get avoiding variable duplication
Thank you!
My usecase was partially motivated by laziness. I wanted a quick way to see if a String was entirely in a set of valid characters in a KMP project, without regex (since I can't find it in common), and didn't want to type them all out, or repeat myself
Copy code
val asciiRanges = listOf(

val hostnameRange: List<Char> = asciiRanges.flatten()

inline fun String.inHostnameRange(): Boolean =
if you just want to create a list of out ranges and individual elements you can use
operator like so:
Copy code
val hostnameChars: List<Char> = ('a'..'z') + ('0'..'9') + '_' + '-'
also, in your case
might be more appropriate then
since you're only checking whether it contains certain elements. To achieve the same but with set you could either use above and convert it to set, or you could use set builder:
Copy code
val hostnameChars: Set<Char> = buildSet {
    this += 'a'..'z'
    this += '0'..'9'
    this += '_'
    this += '-'
🙌 1
By the way, it seems you're validating hostnames and I don't think "_" is a valid part of a hostname (unless the rules have recently changed and I haven't heard about it).
Very well could be @Klitos Kyriacou I got this based on the Wikipedia article for hostnames, which linked to RFC 2181. I also found this SO answer that mentioned it was potentially valid
The other answers though get closer to the No side of the answer though