ant2009
ant2009

Reputation: 22676

smart casting for doing a safe cast

kotlin 1.2.50

I am doing a smart cast and just wondering if this is the correct way to do it. As params.bottomMargin is highlight by the code editor to be Smart cast to android.support.v7.widget.RecyclerView.LayoutParams

    val child = parent.getChildAt(i)
    val params = child.layoutParams
    if(params is RecyclerView.LayoutParams) {
        val dividerTop = child.bottom + params.bottomMargin
        val dividerBottom = dividerTop + drawable.intrinsicHeight

        drawable.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom)
        drawable.draw(c)
    }

Just wondering if there is something I can do more with the above code to cast params to RecyclerView.LayouParams

Many thanks in advance,

Upvotes: 1

Views: 70

Answers (1)

apetranzilla
apetranzilla

Reputation: 5959

This is the correct usage of smart casts. If you want an alternative, you can also use the when statement or a safe cast, like these examples:

when (params) {
    is RecyclerView.LayoutParams -> { /* smart cast here */ }
    else -> { /* optional other cases */ }
}

// casts to RecyclerView.LayoutParams? and then invokes the body of let if not null (when params is a RecyclerView.LayoutParams)
(params as? RecyclerView.LayoutParams)?.let {
     /* smart cast here */
}

Upvotes: 3

Related Questions