https://kotlinlang.org logo
j

Jeisson Sáchica

12/15/2020, 7:43 PM
Should smart casting work normally when using nested
sealed
classes? I see a lot of issues like this https://youtrack.jetbrains.com/issue/KT-13495 marked as fixed a long time ago yet I experience this problem in 1.4.21
Copy code
sealed class User {
    object Unauthenticated: User()
    sealed class Authenticated: User() {
        object Client: Authenticated()
        object Owner: Authenticated()
    }
}

fun getUser(): User {
    return User.Authenticated.Client
}

fun main() {
    when (val user: User = getUser()) {
        is User.Unauthenticated -> { println("Not Authenticated!") }
        is User.Authenticated -> {
            when (user) {
                is User.Authenticated.Client -> { println("Hello Client!") }
                is User.Authenticated.Owner -> { println("Hello Owner!") }
            }
        }
    }
}
The second
when
expression shows the warning:
I can add to the
when
expression
user as Authenticated
but then it is marked as "unnecessary":
r

Rafs

12/15/2020, 8:39 PM
The cast happens during the
is
evaluation that is why your
as
cast has been marked as useless
j

Jeisson Sáchica

12/15/2020, 8:45 PM
Yes, except that if the explicit casting is removed the compiler gives a warning asking for exhaustive checking on the
when
expression, the warning is in the first screenshot
I found two issues related to this problem, one is from 2 years ago https://youtrack.jetbrains.com/issue/KT-29087, and the other is from 4 months ago https://youtrack.jetbrains.com/issue/KT-41305. Both are unassigned so I guess all we can do is wait and ignore the warning
j

Javier

12/15/2020, 9:04 PM
12 Views