Kotlin에서 제네릭 클래스를 동일한 유형의 제네릭 배열에 매핑하는 방법이 궁금합니다.
다음 수업이 주어집니다.
class <T> MyClass(val type : Class<T>) {
fun new() = type.newInstance()
}
나는 다음과 같은 것을 갖고 싶다.
class MyOtherClass {
val map = Map<Class<T>, MyClass<T>>
inline fun <reified T> get() : MyClass<T> {
if(T::class.java in map) {
return map[T::class.java]
} else {
val newInstance = MyClass(T::class.java)
map[T::class.java] = newInstance
return newInstance
}
}
}
그러나 다음과 같은 이유로 작동하지 않습니다.
나는 어떻게 그리고 당신이 그것을 쓸 수 있는지 모르겠지만 논리적 관점에서 나는 다음을 달성하고 싶습니다.
언급했듯이 다음과 같은 작성 방법이 있지만 맵이 컴파일러에게 X 유형의 항목을 가져 오면 MyClass가 반환된다는 것을 알려야하기 때문에 캐스팅 경고를 피하고 싶습니다. X를 입력합니다.
class MyOtherClass {
val map = Map<Class<out Any>, MyClass<out Any>>
inline fun <reified T:Any> get() : MyClass<T> {
if(T::class.java in map) {
return map[T::class.java] as MyClass<T>
} else {
val newInstance = MyClass(T::class.java)
map[T::class.java] = newInstance
return newInstance
}
}
}
도와 주셔서 감사합니다!
Lino와 오프닝 포스트에서 언급했듯이 Something에 대한 일반 정보 T가 손실되기 때문에 경고 없이는 불가능합니다.
또한 *는 Kotlin에서 와일드 카드로 사용할 수 있으므로 다음 접근 방식이 작동합니다 (실제 코드에서 가져옴).
inline fun <reified T> componentManager(): ComponentManager<T> = componentManager(T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T> componentManager(type: Class<T>): ComponentManager<T> {
return when {
componentManagers.containsKey(type) -> {
componentManagers[type] as ComponentManager<T>
}
else -> {
val manager = ComponentManager(initialEntityCapacity, type)
addListener(manager)
componentManagers.put(type, manager)
manager
}
}
}
리노 덕분에!
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다