binding-collection-adapter icon indicating copy to clipboard operation
binding-collection-adapter copied to clipboard

[Suggestion] ktx extensions should return the value to fulfil the chaining pattern

Open martofeld opened this issue 3 years ago • 3 comments

Feature Request

Without using ktx extensions the code looks as follows

OnItemBindClass<MySealedClass>()
    .map(MySealedClass.Impl1::class.java, /*use either overload*/)
    .map(MySealedClass.Impl2::class.java, /*use either overload*/)

using the ktx extension it should look something like the following

OnItemBindClass<MySealedClass>()
    .map<MySealedClass.Impl1>(/*use either overload*/)
    .map<MySealedClass.Impl2>(/*use either overload*/)

but the .map doesn't return the OnItemBindClass instance like it does in java, therefore the chaining pattern is broken

martofeld avatar Apr 20 '21 20:04 martofeld

Agreed

evant avatar Apr 20 '21 21:04 evant

I've been playing around with this a little bit, unfortunately since its an extension function we can not access the generic T in OnItemBindClass<T>. Therefore you need to re-state the T. This is the best I could get to.

inline fun <reified E: T, T> OnItemBindClass<T>.mapKt(
    variableId: Int,
    @LayoutRes layoutRes: Int
): OnItemBindClass<T> =
    map(E::class.java, variableId, layoutRes)

Usage

OnItemBindClass<Any>()
        .map<String, Any>(BR.item, R.layout.item_header_footer)
        .map<MutableItem, Any>(BR.item, R.layout.item)

If such is the case, I think the apply solution will still be the best

martofeld avatar Apr 20 '21 23:04 martofeld

I've been playing around with this a little bit, unfortunately since its an extension function we can not access the generic T in OnItemBindClass<T>. Therefore you need to re-state the T. This is the best I could get to.我一直在玩这个,不幸的是,由于它是一个扩展函数,我们无法访问OnItemBindClass<T>中的通用T 。因此您需要重新声明T 。这是我能达到的最好的。

inline fun <reified E: T, T> OnItemBindClass<T>.mapKt(
    variableId: Int,
    @LayoutRes layoutRes: Int
): OnItemBindClass<T> =
    map(E::class.java, variableId, layoutRes)

Usage 用法

OnItemBindClass<Any>()
        .map<String, Any>(BR.item, R.layout.item_header_footer)
        .map<MutableItem, Any>(BR.item, R.layout.item)

If such is the case, I think the apply solution will still be the best如果是这样的话,我认为 apply 解决方案仍然是最好的

It can be changed to this way more convenient to use inline fun <reified E : Any> OnItemBindClass<Any>.map( variableId: Int, @LayoutRes layoutRes: Int ): OnItemBindClass<Any> = map(E::class.java, variableId, layoutRes)

Usage

val item=OnItemBindClass<Any>() .map<String>(BR.item, R.layout.item_header_footer) .map<MutableItem>(BR.item, R.layout.item)

lhjgege avatar Sep 12 '24 02:09 lhjgege