https://kotlinlang.org logo
Title
o

otakusenpai

02/05/2019, 1:57 PM
Hello, I've a piece of function which does the following:
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

spand

02/05/2019, 2:00 PM
Put them in a set and use
contains()
?
r

Rafal

02/05/2019, 2:00 PM
there is a CharRange in kotlin
j

Jake

02/05/2019, 2:01 PM
This should work, I haven’t tried it though.
inline fun letterInRange(char: Char) = when(char) {
    in 'a'..'h' -> true
    else -> false
}
r

Rafal

02/05/2019, 2:01 PM
fun main(args : Array<String>) {
	
    val charRange = CharRange('a', 'g')
    print(charRange.contains('b')) //true
    print(charRange.contains('z')) //false
}
☝️ 2
j

Jake

02/05/2019, 2:01 PM
Yea use @Rafal’s answer.
t

Tsvetozar Bonev

02/05/2019, 2:02 PM
('a'..'b').contains('a')
d

Dias

02/05/2019, 2:05 PM
'a' in 'a'..'h'
h

hudsonb

02/05/2019, 2:33 PM
^
inline fun letterInRange(char: Char): Boolean = char in 'a'..'h'
o

otakusenpai

02/05/2019, 2:34 PM
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

hudsonb

02/05/2019, 2:41 PM
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

Alan Evans

02/05/2019, 2:49 PM
P.S. No good reason to use
inline
here
as for how it works if you put this in IDE (IntelliJ):
fun letterInRange(char: Char): Boolean = char.compareTo('a') >= 0 && char.compareTo('h') <= 0
It will suggest:
fun letterInRange(char: Char): Boolean = char >= 'a' && char <= 'h'
And then it will suggest a range check:
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

otakusenpai

02/06/2019, 3:36 PM
Hmm thnx for the insight
👍 1