Upper bound generics cannot have default parameter?

For example:

interface A<R>

object B : A<Int>

fun <C : A<Int>> f(b: C = B) {//Type Mismatch: Required C, Found:B
}

fun main(args: Array<String>) {
  f(B)// works 
}

In this example, we cannot set default parameter for b using B, but can pass B as parameter to f.

Is there any way to set default type?

The compiler cannot guarantee that your default can always be assigned to the actual generic type, so it disallows this. For example:

object NotB : A<Int>

Now the actual declaration of f would be: f(b: NotB = B)

1 Like

You can create an overloaded function that provides the default value:

fun f() = f(B)

Since this works, it really feels like it should work with default parameter, too. But I can see how this might be a hard problem to solve for the compiler.

Yeah. I think this may be related to Allow typealias to have the same name as generic class - #6 by abreslav. This requires default type from default parameter.