kotlin geneirc with vararg parameter

半腔热情 提交于 2020-06-29 04:17:10

问题


Now I am working on some problems about passing the function as parameter in a function with vararg parameter with generic parameter. The below code works for one function as parameter into other

function like that funA(funB(parameter):return1):return2

but when i make function like that

funA(vararg funB(parameter):return1):return2

it doesn't works. I have tried somethings like Array or KFunction1

ViewModel

fun callMultipleAPI( vararg  observable: Observable<Any>):LiveData<Boolean>{
.....
return progressDialogData!!
}

fun callGetTeammateListAPITEST():Observable<Any>{
....
return repo.callGetMessageSumTEST()!!
}

Fragment

fun test(){
EasyDialog<Observable<Any>,LiveData<Boolean>>(ctx, true,viewModel!!::callGetTeammateListAPITEST,recallFunctionWithFunction = viewModel!!::callMultipleAPI).createNativeNetworkDialog2()
}

EasyDialog

class EasyDialog<T,V> {
var canCancel: Boolean = true
var recallFunction: (() -> T)? = null
var recallFunctionWithValue: ((value: T) -> Unit)? = null
var context: Context? = null
var value: T? = null
var functionPara :(()->T)? = null
var recallFunctionWithFunction:((T) -> V)? = null



constructor(
context: Context?, canCancel: Boolean, value: ()->T, recallFunctionWithFunction:  (T) -> V  ){
this.context = context
this.canCancel = canCancel
this.functionPara = value
this.recallFunctionWithFunction = recallFunctionWithFunction
}

fun createNativeNetworkDialog2() {
...

    functionPara?.let{ functionPara->{ recallFunctionWithFunction?.let {
            recallFunctionWithFunction-> compose<T,V>(recallFunctionWithFunction  ,functionPara).invoke()
    }}}
}

}

    fun <T, V> compose( f: (T) -> V,    g:() -> T ): () -> V {
            return {  f(g()) }
}

But it only allow the function without vararg parameter. I try to make something out as below

var functionPara :(()->T)? = null
var recallFunctionWithFunction:( (Array<out T>) -> V)? = null
    constructor(
    context: Context?, canCancel: Boolean, value: ()->T, recallFunctionWithFunction:   (Array<out T>) -> V  ){
    this.context = context
    this.canCancel = canCancel
    this.functionPara = value
    this.recallFunctionWithFunction = recallFunctionWithFunction
}
    fun <T, V> compose( f: (Array<out T>)->V,   vararg g:() -> T ): () -> V {

        return {  f(g()) }
}

but it shows the type mismatch

type Mismatch

can anyone help?


回答1:


It's because g is an array of functions. Not a function. Looks like you have call all these functions and collect the results:

inline fun <reified T, V> compose(crossinline f: (Array<out T>) -> V, vararg g: () -> T): () -> V {
    val results = g.map { it() }
    return { f(results.toTypedArray()) }
}

You have to mark your function as inline if want to use arrays here



来源:https://stackoverflow.com/questions/62260177/kotlin-geneirc-with-vararg-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!