我需要创建一个数据类:
data class MyClass(val b: Boolean,
val s: String,
val flags: Map<Key<T>, T>)
由于“未解析的引用:T”
,因此无法编译在flags
地图中,我需要Key<String>, String
和Key<Int>, Int
对,但不是Key<String>, Int
关于如何实现这一目标的任何想法?
答案 0 :(得分:3)
您必须定义该类的通用:
data class MyClass<T>(val b: Boolean,
val s: String,
val flags: Map<Key<T>, T>)
答案 1 :(得分:2)
您无法通过类型系统直接执行此操作,您必须使用封装以确保键和值的类型一致。 This problem exists in Java as well.
其他人给出的解决方案并不起作用,因为您只能将一种类型的键/值放入地图中(有gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
的想法有些瑕疵) :
Map<Key<T>, T>
或:
val map = mutableMapOf<Key<String>, String>() // what to put as generic params here?
map[Key<String>()] = "blah" // works
map[Key<Int>()] = 3 // doesn't work!
map[Key<Int>()] = "blah" // compiler error (as intended)
您必须在地图周围编写自己的封装,以确保密钥始终与值匹配:
val map = mutableMapOf<Key<*>, Any?>()
map[Key<String>()] = "blah" // works
map[Key<Int>()] = 3 // works
map[Key<Int>()] = "blah" // works, but is wrong.
(如果您愿意,可以添加不可变的超级界面)
然后将其用作字段:
class MutableKeyMap {
private val map = mutableMapOf<Key<*>, Any?>() // private / encapsulated
operator fun <T> get(key: Key<T>): T {
return map[key] as T
}
operator fun <T> set(key: Key<T>, value: T): Unit { // Key's T must match value's type.
map[key] = value
}
}
...
data class MyClass(val b: Boolean,
val s: String,
val flags: MutableKeyMap)
答案 2 :(得分:1)
你已经忘记了这一点:
data class MyClass<T>(val b: Boolean,
// ----------------^
val s: String,
val flags: Map<Key<T>, T>)
有关详细信息:Generics