简体   繁体   English

与Kotlin中的通用类型配对

[英]Pair with generic type in Kotlin

I want to create a Pair which should take a generic type. 我想创建一个Pair应该采取一个泛型类型。 I mean, I can pass a String to Int . 我的意思是,我可以将String传递给Int How can I achieve that? 我该如何实现?

Example with the current behavior: 当前行为的示例:

val liveData = MutableLiveData<Pair<Boolean, Int>>()

Expectation: 期望:

val liveData = MutableLiveData<Pair<T, T>>()

try this 尝试这个

class Abc<T, U> {

    val liveData = MutableLiveData<Pair<T, U>>()

}


fun <T, U> Abc1(): MutableLiveData<Pair<T, U>> {
   return MutableLiveData<Pair<T, U>>()
}
val liveData = Abc<String, Int>()

If you want to pass either String or Int, a sealed class may be the right choice, rather than a generic. 如果要传递String或Int,则密封类可能是正确的选择,而不是泛型。

In your case something like: 在您的情况下,例如:

sealed class StrInt
data class Numeric(val value:Int):StrInt()
data class Alphanum(val value:String):StrInt()

val a:Pair<StrInt, StrInt> = Numeric(10) to Alphanum("qwerty")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM