android - 泛型函数签名中 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>
part 指定类型参数upper
bound
上的一个。简单来说,它意味着必须是一个。generic
T
T
subtype
Observable<String>
使用 时generic
types
,您可以将单个指定upper
bound
为
// 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)
但是如果你需要指定多个upper
bounds
,那么你必须使用where
clause
as
// 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 子句。
推荐阅读
- javascript - svelte 中的 API 请求
- outlook - Outlook 在启动时忽略加载项的 HKEY_LOCAL_MACHINE 条目
- swift - 返回 String 的 metadata?.downloadURL().absoluteString 更新
- javascript - 在javascript中调用同一文件中的函数
- c# - 组合来自不同对象的 JSON 字符串值
- c# - C#,EF 6 - DBContext 未打开连接
- python - 如何在 Python、Flask 中制作日期过滤栏?
- python-3.x - 比较两个变量python 3时收到类型错误
- windows - rust File::create() 有时会返回操作系统错误 32
- python - 用于计算平方根的 Python 程序中没有返回值