Can anybody explain this piece of code from one of...
# getting-started
e
Can anybody explain this piece of code from one of the example in the "_The in Keyword_" section from the book " Atomic Kotlin "?
Copy code
fun main(args: Array<String>) {
  println("ab" in "aa".."az")
  println("ba" in "aa".."az")
}

/* Output:
true
false
*/
I can understand that you can validate the range between 'a'..'z'. I'm just not quite able to grasp the idea of validating 'aa'..'az'
s
well, much like
a..z
would contain
b, c, d, e...
,
aa..az
would include
ab, ac, ad, ae...
and so on up to
az
✔️ 1
👍🏻 1
d
It is similar to
"aa" <= "ab" && "ab" <= "az"
.
👍🏻 1
✔️ 3
What he said.
e
Thx. Now makes sense.
a
I really like this example (stolen from a Jetbrains presentation):
Kotlin falls flatly in the range between between Java and Scala
Copy code
"kotlin" in "java".."scala"
😁 3
👍 2
e
@andym Thx. very much for the example. It actually got me more confused (but in a good way) So I've tried to figure out how could this be working behind the scenes, by creating my own function:
stringIsIn()
This is how I understand this works. Let me know if I'm wrong.
Copy code
fun main() {
  var a = "akkotlin"
  var b = "akjava"
  var c = "akscala"
  println(stringIsIn(a,b,c))
}

fun stringIsIn(a: String, b: String, c: String): Boolean {
  for (i in 0..a.lastIndex)
    if (i <= b.lastIndex && i <= c.lastIndex)
      if ((b[i] != c[i] && a[i] == b[i]) || a[i] != b[i] && b[i] != c[i] || a[i] == b[i] && b[i] == c[i])
        return a[i] >= b[i] && a[i] <= c[i]
  return false
}
a
It's just sorting order. `String`s are `Comparable`:
Copy code
fun stringIsIn(a: String, b: String, c: String): Boolean {
        return a.compareTo(b) >= 0 && a.compareTo(c) <= 0
    }
Which the IDE tells you can be:
Copy code
fun stringIsIn(a: String, b: String, c: String): Boolean {
        return a >= b && a <= c
    }
Which the IDE tells you can be:
Copy code
fun stringIsIn(a: String, b: String, c: String): Boolean {
        return a in b..c
    }
Which can generically be:
Copy code
fun <T:Comparable<T>> tIsIn(a: T, b: T, c: T): Boolean {
        return a.compareTo(b) >= 0 && a.compareTo(c) <= 0
    }
Which is also:
Copy code
fun <T:Comparable<T>> tIsIn(a: T, b: T, c: T): Boolean {
        return a in b..c
    }
🤩 1
👍 3