Seaskyways
Seaskyways

Reputation: 3795

Smart cast variable in lambda kotlin workaround

I have past a lambda today that has a variable which is of unknown type , and inside the when..is condition , the variable can't smart cast to the type in the is condition ... it gives that it is impossible since the variable is a Public Api , is there a workaround to this ?

enter image description here

Upvotes: 1

Views: 2534

Answers (3)

mfulton26
mfulton26

Reputation: 31254

You can create a more convenient onBind extension function which has item, view, etc. passed to the lambda instead of receiving an ItemViewTypePosition:

inline fun LastAdapter.Builder.onBind(crossinline f: (item: Any, view: View, type: Int, position: Int) -> Unit): LastAdapter.Builder {
    return onBindListener(object : OnBindListener {
        override fun onBind(item: Any, view: View, type: Int, position: Int) {
            f(item, view, type, position)
        }
    })
}

Usage:

builder.onBind { item, view, type, position ->
    when (item) {
        is Product -> view.number_sold.text = item.price.toString()
    }
}

Upvotes: 2

voddan
voddan

Reputation: 33819

Another way of doing it is to make the cast yourself:

.onBind {
    when(item) {
        is Product -> view.number_sold_text = (item as Product).price.toString()
    }
}

Upvotes: 0

Seaskyways
Seaskyways

Reputation: 3795

I have found a simple workaround which is defining a val to equal the wanted variable and use that instead like so ...

enter image description here

Upvotes: 1

Related Questions