The in Keyword

The in keyword checks whether a value is within a range.

// InKeyword/MembershipInRange.kt fun main(args: Array<String>) { val percent = 35 println(percent in 1..100) } /* Output: true */

In Booleans, you learned to check bounds explicitly:

// InKeyword/MembershipUsingBounds.kt fun main(args: Array<String>) { val percent = 35 println(0 <= percent && percent <= 100) } /* Output: true */

x in 0..100 is logically equivalent to saying 0 <= x && x <= 100. IntelliJ IDEA even suggests automatically replacing the explicit form with the short one. The in form is easier to read and understand.

Although the in keyword is used both for membership and for iteration, the meaning is different. An in that’s a part of a for loop means iteration, otherwise in checks membership:

// InKeyword/IterationVsMembership.kt fun main(args: Array<String>) { val values = 1..3 for (v in values) println("iteration $v") val v = 2 if (v in values) println("$v is a member of $values") } /* Output: iteration 1 iteration 2 iteration 3 2 is a member of 1..3 */

The in keyword is not limited to ranges. You can also check whether a character is a part of a String. The following example uses in instead of the hasChar() from HasChar.kt in the previous atom:

// InKeyword/InString.kt fun main(args: Array<String>) { println('t' in "kotlin") println('a' in "kotlin") } /* Output: true false */

Later in the book we’ll see that in works with other types, as well.

Here, in tests whether a character belongs to a range of characters:

// InKeyword/CharRange.kt fun isDigit(ch: Char) = ch in '0'..'9' fun isNotDigit(ch: Char) = ch !in '0'..'9' // [1] fun main(args: Array<String>) { println(isDigit('a')) println(isDigit('5')) println(isNotDigit('z')) } /* Output: false true true */

You can create a Double range, but checking for membership is the only thing you can do with it:

// InKeyword/FloatingPointRange.kt fun inFloatRange(n: Double) { val r = 1.0..10.0 println("$n in $r? ${n in r}") } fun main(args: Array<String>) { inFloatRange(0.999999) inFloatRange(5.0) inFloatRange(10.0) inFloatRange(10.0000001) } /* Output: 0.999999 in 1.0..10.0? false 5.0 in 1.0..10.0? true 10.0 in 1.0..10.0? true 10.0000001 in 1.0..10.0? false */

The .. operation is the only one allowed to create floating-point ranges; until is not implemented because excluding a floating-point number as an endpoint is not meaningful.

You can check whether a string is a member of a range of strings:

// InKeyword/StringRange.kt fun main(args: Array<String>) { println("ab" in "aa".."az") println("ba" in "aa".."az") } /* Output: true false */
Here we use alphabetic comparison.

Previous          Next

©2018 Mindview LLC. All Rights Reserved.