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

@Test
fun `toRange creates a range with a single value`() {
    val range = 'Z'.toRange()
    assertEquals('Z', range.first)
    assertEquals('Z', range.last)
}
1
My primary complaint with
'Z'..'Z'
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
s
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
toRange
extension is as good as you can get avoiding variable duplication
1
z
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(
    'a'..'z',
    '0'..'9',
    '-'.range,
    '_'.range,
)

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

inline fun String.inHostnameRange(): Boolean =
    all(hostnameRange::contains)
s
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
Set
might be more appropriate then
List
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
k
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).
z
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 https://stackoverflow.com/a/2183140
The other answers though get closer to the No side of the answer though