带vararg参数的kotlin geneirc。

问题描述 投票:0回答:1

现在我正在处理一些关于在一个函数中用通用参数传递vararg参数的问题。下面的代码适用于一个函数作为参数传入其他函数的情况

这样的函数 funA(funB(parameter):return1):return2

但当我做这样的函数时

funA(vararg funB(参数):return1):return2

它不工作。我试过像Array或KFunction1这样的东西。

查看模型

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

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

片段

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()) }
}

但它只允许函数不含vararg参数。我试着做了如下的东西

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()) }
}

但它显示类型不匹配

错位型

谁能帮帮我?

kotlin generics variadic-functions
1个回答
0
投票

这是因为 g 是一个函数数组。不是一个函数。看起来你要调用所有这些函数并收集结果。

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()) }
}

你必须把你的函数标记为 inline 如果想在这里使用数组

© www.soinside.com 2019 - 2024. All rights reserved.