Upper bound generics cannot have default parameter?


#1

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.


#2

Is there any way to set default type?


#3

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)


#4

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.


#5

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