Hello, I've a piece of function which does the fol...
# getting-started
o
Hello, I've a piece of function which does the following:
Copy code
inline fun letterInRange(char: Char): Boolean = char.compareTo('a')  || char.compareTo('b') ||
                                                   char.compareTo('c') || char.compareTo('d') ||
                                                   char.compareTo('e') || char.compareTo('f') ||
                                                   char.compareTo('g') || char.compareTo('h')
Is there a way to shorten the function a bit more? I mean there are too many cases(and yes its giving an error too....)
s
Put them in a set and use
contains()
?
r
there is a CharRange in kotlin
j
This should work, I haven’t tried it though.
Copy code
inline fun letterInRange(char: Char) = when(char) {
    in 'a'..'h' -> true
    else -> false
}
r
Copy code
fun main(args : Array<String>) {
	
    val charRange = CharRange('a', 'g')
    print(charRange.contains('b')) //true
    print(charRange.contains('z')) //false
}
☝️ 2
j
Yea use @Rafal’s answer.
t
Copy code
('a'..'b').contains('a')
d
'a' in 'a'..'h'
h
^
inline fun letterInRange(char: Char): Boolean = char in 'a'..'h'
o
wow thnx guys a lot ❤️
i think char in 'a'..'h' is more concise...can you tell how it works? i can see tht it makes a CharArray of 'a' to 'h'
nvm i see now
h
Can actually be a bit more concise by removing the explicit return type:
inline fun letterInRange(char: Char) = char in 'a'..'h'
The error in your original version was due to
compareTo
returning an
Int
, which you can't do boolean logic on (
||
)
a
P.S. No good reason to use
inline
here
as for how it works if you put this in IDE (IntelliJ):
Copy code
fun letterInRange(char: Char): Boolean = char.compareTo('a') >= 0 && char.compareTo('h') <= 0
It will suggest:
Copy code
fun letterInRange(char: Char): Boolean = char >= 'a' && char <= 'h'
And then it will suggest a range check:
Copy code
fun letterInRange(char: Char): Boolean = char in 'a'..'h'
so that kind of explains how it works as all these pieces of code are equivalent. Note that Range checks can be used on any
Comparable
Also note that it actually does not "create" a range instance or a
CharArray
for this. i.e. it is not allocating an object to do this check, it's just a shorthand.
2
o
Hmm thnx for the insight
👍 1