【问题标题】:how to specify a generic data type that extends from a specific class如何指定从特定类扩展的通用数据类型
【发布时间】:2019-07-08 13:03:10
【问题描述】:

我是新的 kotlin,我想知道如何为方法提供通用数据类型作为参数。在java中

methods(<? extends Class1>)

请查看下面发布的代码,并告诉我如何重构它以适应提供的评论。

更新

   var fragTransactionInstance = getFragmentManagerInstance()?.let {
        it.getFragmentTransactionInstance()
            ?.replaceTransaction(R.id.fragLeft, fragmentLeft)//RequiredTypeVariable (T)Found: FragmentLeft
            ?.replaceTransaction(R.id.fragRight, fragmentRight)
    }?.also {
        it.commit()
    }

代码

 fun FragmentTransaction.replaceTransaction(layout: Int, fragment : Fragment): FragmentTransaction {
    return this.replace(layout, fragment)
}
//the second parameter must be any parameter that extends Fragment. e.g: <? extends Fragment>

【问题讨论】:

    标签: android generics kotlin generic-collections


    【解决方案1】:

    查看下面的解决方案,在 Kotlin 中使用泛型创建函数:

    fun <T : SomeClass> someFun(t: T) {
    
    }
    

    在你的情况下,它会像:

    fun <T : Fragment> FragmentTransaction.replaceTransaction(layout: Int, t: T): FragmentTransaction {
        return this.replace(layout, t)
    }
    

    这里,t 应该是Fragment 类型。

    请参阅 here 了解更多信息。

    【讨论】:

    • 请查看上面添加的更新部分...我按照您的建议修改了代码..但是,我收到了更新部分中所述的错误
    • 您的情况中的 fragmentLeftfragementRight 是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多