为什么我不能在Kotlin中定义<t where =“” t =“”:=“” charsequence,=“” t =“”:=“” appendable =“”>?

时间:2018-07-30 08:32:02

标签: android kotlin

代码A定义了带有参数约束的通用!!

1:我认为代码A很难理解,也许代码B是好的,对吧?

2:还有,我认为fun ensureTrailingPeriod随代码A返回ensureTrailingPeriod,但代码C是错误的,我该如何解决?

代码A

Unit

代码B

fun <T> ensureTrailingPeriod(seq: T)
    where T : CharSequence, T : Appendable{
    if (!seq.endsWith('.')) {
        seq.append('.')
    }
}

代码C

fun <T where T : CharSequence, T : Appendable> ensureTrailingPeriod1(seq: T)  {
    if (!seq.endsWith('.')) {
        seq.append('.')
    }
}

1 个答案:

答案 0 :(得分:3)

  1. 这实际上就是该语言的语法,必须使用where定义多个约束,并且它们必须位于函数标头的末尾,而不是单个约束所在的位置。

  2. 任何显式返回类型也位于where约束之前:

    fun <T> ensureTrailingPeriod(seq: T): Unit where T : CharSequence, T : Appendable {
        if (!seq.endsWith('.')) {
            seq.append('.')
        }
    }
    

作为参考,您也可以在Kotlin grammar中找到它:

function (used by memberDeclaration, declaration, topLevelObject)
  : modifiers "fun"
      typeParameters?
      (type ".")?
      SimpleName
      typeParameters? valueParameters (":" type)?
      typeConstraints
      functionBody?
  ;

这清楚地告诉您函数声明的不同部分的顺序。首先是修饰符(可见性,中缀等),然后是fun关键字,然后是类型参数,以防万一,该函数是扩展名,名称,参数列表,可选的返回类型,最后是函数主体之前的类型约束。