HelloCW
HelloCW

Reputation: 2325

Why can't I define <T where T : CharSequence, T : Appendable> in Kotlin?

Code A define a generic fun ensureTrailingPeriod with parameter restrain.

1: I think Code A is hard to understand, and maybe Code B is good, right?

2: And more, I think that ensureTrailingPeriod return Unit with Code A, but Code C is wrong, how can I fix it?

Code A

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

Code B

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

Code C

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

Upvotes: 1

Views: 67

Answers (1)

zsmb13
zsmb13

Reputation: 89638

  1. That's literally just what the syntax of the language is, multiple constraints have to be defined with where, and they have to be at the end of the function header, and not where single constraints go.

  2. Any explicit return types are also before the where constraints:

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

For reference, you can find this in the Kotlin grammar as well:

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

This clearly tells you what order the different parts of a function declaration come in. First, there are modifiers (visibility, infix, etc), then the fun keyword, then type parameters, the receiver type in case the function is an extension, the name, the parameter list, the optional return type, and finally the type constraints before the body of the function.

Upvotes: 3

Related Questions