kotlin에서 Promise 클래스를 작성하고 싶습니다. 이 클래스는 제네릭 유형을 사용합니다. 형식은 nullable 형식 일 수도 있습니다. 소비자를 호출 할 때 유전자 유형이 nullable이면 값은 null이 될 수 있습니다. 그렇지 않은 경우 값을 개체로 설정해야합니다. kotlin 컴파일러는 다음 메시지를 표시합니다. '값'이 이번에 변경 될 수있는 변경 가능한 속성이기 때문에 'T'로 스마트 캐스트가 불가능합니다.
이 메시지가 표시되는 이유를 이해하지만 현재 값이 정확해야합니다. 이 클래스를 어떻게 컴파일 할 수 있습니까? 나는 값에 접근하려고 !! 하지만 null 을 사용한 내 테스트 는 NPE로 실패합니다.
java.lang.NullPointerException
at test.Promise.resolve(App.kt:20)
at test.AppTest.testPromiseNull(AppTest.kt:31)
class Promise<R> {
private var resolved = false
private var value: R? = null
var then: Consumer<R>? = null
fun resolve(r: R) = synchronized(this) {
if (resolved) error("Promise already resolved!")
value = r
resolved = true
then?.accept(value) // Smart cast to 'T' is impossible, because 'value' is a mutable property that could have been changed by this time*
}
fun then(consumer: Consumer<R>) = synchronized(this) {
if (then != null) error("Just one consumer is allowed!")
then = consumer
val value = value
if (resolved) {
consumer.accept(value) // Smart cast to 'T' is impossible, because 'value' is a mutable property that could have been changed by this time*
}
}
}
@Test fun testPromise() {
val promise = Promise<String>()
var resolved = false
promise.then {
assertEquals(it, "hello" )
resolved = true
}
promise.resolve("hello")
assert(resolved)
}
@Test fun testPromiseNull() {
val promise = Promise<String?>()
var resolved = false
promise.then {
assertNull(it)
resolved = true
}
promise.resolve(null)
assert(resolved)
}
업데이트 나는 약간의 도움말 기능을 만들었습니다.
private fun <T> uncheckedCast(t: T?): T {
@Suppress("UNCHECKED_CAST")
return t as T
}
당신을 위해 resolve
기능, 당신은 이미 당신이 대신 사용할 수있는 불변의 매개 변수 값을 가지고있다.
fun resolve(r: R) = synchronized(this) {
if (resolved) error("Promise already resolved!")
value = r
resolved = true
then?.accept(r)
}
다른 경우에는 컴파일러보다 더 많이 알고 있으므로 명시 적 캐스트를 수행하고 경고를 억제 할 수 있습니다.
fun then(consumer: Consumer<R>) = synchronized(this) {
if (then != null) error("Just one consumer is allowed!")
then = consumer
if (resolved) {
@Suppress("UNCHECKED_CAST")
consumer.accept(value as R)
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다