我有两个数据类
data class Card(val code: String?, val caption: String?, val icon: String?)
data class Currency(val code: String?, val caption: String?, val descr: String?)
分为以下列表:List<Card> and List<Currency>
,我在调用一个函数时用作参数。参数类型定义为List<Any>
。如何在类或函数内部确定数据类型?
那是卡清单还是货币清单?
这是Kotlin上的Android应用程序
class SpinnerAdapter(val context: Context, var name: List<Any>): BaseAdapter() {
init {
if (name.contains(Card)) { //is list of Card?
}
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
...
答案 0 :(得分:3)
我认为您可以使用Kotlin在此处提供的炫酷功能。 例如:
class SpinnerAdapter(var name: List<Any>) {
init {
when(name.first()){
is Card -> {
// do something
}
is Currency -> {
// do something
}
else -> // do something
}
}
}
此解决方案依赖于任何列表都可以具有所有卡或所有货币。如果list可以包含混合项目,则应在for之前运行for循环,并让when块确定流程。
答案 1 :(得分:0)
Amazia的答案是可行的,但是您可以通过实现像这样的密封类来改进它:
CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2182,localhost:2182,localhost:2183", retryPolicy);
有关Kotlin中密封类的更多信息:https://kotlinlang.org/docs/reference/sealed-classes.html
这使您可以对PaymentMethods列表进行详尽的when子句,如下所示(无需else分支):
sealed class PaymentMethod {
abstract val code: String?
abstract val caption: String?
data class Card(override val code: String?, override val caption: String?, val icon: String?) : PaymentMethod
data class Currency(override val code: String?, override val caption: String?, val descr: String?) : PaymentMethod
}
如果您愿意,也可以在流中使用此穷举:
class SpinnerAdapter(var name: List<PaymentMethod>) {
init {
when(name.first()){
is Card -> {
// do something
}
is Currency -> {
// do something
}
}
}