https://kotlinlang.org logo
#announcements
Title
# announcements
s

Stephan Schroeder

07/01/2019, 1:45 PM
if don’t understand why I have to explicitly do a non-null cast
Copy code
if (prioritizedViews != null) {
            prioritizedViews as PrioritizedViews<CareHomeView>
        } else ...
in
Copy code
class CareHomeCombinedView(
    private var prioritizedViews: PrioritizedViews<CareHomeView>? = null
) {

    private val views: PrioritizedViews<CareHomeView> =
        if (prioritizedViews != null) {
            prioritizedViews as PrioritizedViews<CareHomeView>
        } else {
            PrioritizedViews(              
            )
        }
}

class PrioritizedViews<T>(
    vararg viewsByPriority: T?
)

interface CareHomeView {}
the type inference normally includes the null-check! What is different this time? Here the link to the playground: https://pl.kotl.in/js_ASkwV9
d

Dias

07/01/2019, 1:50 PM
like the error message says by the time following line are executed prioritizedViews can become null again
👍 1
s

Stephan Schroeder

07/01/2019, 1:50 PM
indeed, making the
prioritizedViews
a
val
fixes it!
a

adamd

07/01/2019, 4:13 PM
In general, using `val`s instead of `var`s make Kotlin a lot easier to use 😉
2 Views