Is there any YouTrack issue to make the compiler a...
# getting-started
k
Is there any YouTrack issue to make the compiler allow the following, or is there a reason it can't?
Copy code
fun foo(n: Int): Int {
    require(n >= 1 && n <= 3)
    return when (n) {
        1 -> 10
        2 -> 20
        3 -> 30
    }
}
h
It is possible with enums: https://kotlinlang.org/docs/whatsnew2220.html#data-flow-based-exhaustiveness-checks-for-when-expressions So maybe you could refactor your code to enums. And add a youtrack issue for Ints.
👀 1
j
+1 for a YouTrack, this could be a pretty neat feature 👀
the data-flow based exhaustiveness checks are https://youtrack.jetbrains.com/issue/KT-8781/Consider-making-smart-casts-smart-enough-to-handle-exhaustive-value-sets and currently look targeted to be stable in 2.3.0
but Kotlin doesn't treat
Int
as an enumeration of …, -1, 0, 1, 2, … so it won't work with that. probably needs a more efficient representation at a minimum
j
@Klitos Kyriacou the compiler can't do it because there's no way to represent this runtime check, and therefore this number subset range, as a Kotlin type.
e
@Jose Fort that's not completely true. the Kotlin compiler can represent types that cannot be expressed in code, and the new dataflow analysis can track subsets of a type that have been excluded. however it only works for sealed types and enums, not numeric types
j
@ephemient yeah, that's more or less what I meant, but wrote unclearly. subsets of numeric values like ranges are not subsets of types. Therefore a runtime check of such, is incompatible with current type inference.
e
FWIW there is a feature request https://youtrack.jetbrains.com/issue/KT-51417/Restricted-types but it's probably not going to happen soon
🙏 1