创建一个具有Int的BehaviourSubject [英] Creating a BehaviourSubject with an Int
问题描述
如何创建带有Int的此Subject的实例:
How can I create an instance of this Subject with an Int:
class NonNullableBehaviourSubject<T : Any>(defaultValue: T) : Subject<T>() {
private val behaviourSubject = BehaviorSubject.createDefault<T>(defaultValue)
}
然后我像这样创建NonNullableBehaviourSubject的实例:
I then create an instance of NonNullableBehaviourSubject like this:
val emailValidationSubject = NonNullableBehaviourSubject(Int)
但是随后我得到了一个编译错误:
But I then get a compile error using this:
emailValidationSubject.onNext(error?.errorResId)
我得到的编译错误是:
Required: Companion.Int
Found: Int?
此外,Int不能为空.但是,NonNullableBehaviourSubject确实定义了可为空的参数.
Also, Int must not be nullable. Yet, NonNullableBehaviourSubject does define a nullable parameter.
推荐答案
您的error
对象具有可为空的类型,并且您对其使用了安全调用(?.
),因此整个表达式都是可为空的.
要使值不可为空,您可以断言值不为空(如果error
为null
,error!!.errorResId
将崩溃,如果整个表达式为null,则error?.errorResId!!
将崩溃)或为null情况提供后备值((error ?: DEFAULT_ERROR).errorResId
或error?.errorResId ?: DEFAULT_ERROR_RES
).
Your error
object has nullable type, and you use safe call (?.
) on it, so the whole expression is nullable.
To make the value non-nullable you can either assert value is not null (error!!.errorResId
will crash if error
is null
, error?.errorResId!!
will crash if the whole expression is null) or provide the fallback value for null case ((error ?: DEFAULT_ERROR).errorResId
or error?.errorResId ?: DEFAULT_ERROR_RES
).
这篇关于创建一个具有Int的BehaviourSubject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!