where关键字在泛型函数中有什么用途'签名



我重构了这个片段:

remark.observeOn(mainThread())
.subscribe { remark ->
remark_box.visible = remark.isNotEmpty()
remark_tv.text = remark
}
.addTo(CompositeDisposable())

使用这个扩展,但我对什么是: Disposable where T : Observable<String>感到困惑请有人能解释一下吗?

remark.bindTo(remark_tv)
.addTo(CompositeDisposable())

fun <T> T.bindTo(textView: TextView): Disposable where T : Observable<String> {
return observeOn(mainThread())
.subscribe { remark ->
textView.text = remark
}
}

: Disposable表示函数的返回类型为Disposable
where T : Observable<String>部分在generic类型参数T上指定一个upperbound。简单地说,它意味着CCD_ 9必须是CCD_ 11的CCD_。

使用generictypes时,可以将单个upperbound指定为

// This function can only be called with types implementing Collection<Int>
fun <T: Collection<Int>> someFun(first: T, second: T)
// If you try to call it as following, it will not compile
someFun(listOfStrings, listOfStrings)

但如果需要指定多个upperbounds,则必须使用whereclause作为

// This function can only be called with types implementing Iterable<Int>
// as well as Serializable
fun <T> someFun(first: T, second: T): Int where  T: Iterable<Int>,T: Serializable
// This does not work, you can not comma separate the upper bounds
fun <T: Iterable<Int>, Serializable> someFun(first: T, second: T): Int

正如文件所述

在尖括号内只能指定一个上界。如果同一类型参数需要多个上界,我们需要单独的where条款。

最新更新