首页 > 解决方案 > 泛型函数签名中 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
        }
}

标签: androidgenericskotlinrefactoringrx-java

解决方案


: Disposable表示您的函数的返回类型是Disposable.
where T : Observable<String>part 指定类型参数upper bound上的一个。简单来说,它意味着必须是一个。genericTTsubtypeObservable<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 clauseas

// 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 子句。


推荐阅读