I noticed that generics types cannot have default ...
# language-evolution
p
I noticed that generics types cannot have default values. Is this something that can be added in the future? Since now it seems I have to result into using the Java pattern that Kotlin was suppose to fix. Perhaps there are there some corner cases that prevent this from being supported? Just a very simple example to highlight my question (and yes, as a code snippet it doesn't make much sense ;)
Copy code
// Java approach works of course
fun <T> test1(a: T) = a

fun test1() = test1("World")


// Not allowed, gives an error
fun <T> test2(a: T = "World") = a
e
what if
T != String
?
defaults do work:
Copy code
fun <T : Any> test3(a: T? = null) = a
but you have to provide a value that is actually valid
p
I was always under the impression that a default value is just syntactic sugar. So when it is valid to pass a string as argument, it is also valid to use a string a default value. Of course when you pass for example an int the default value is not used and <T> resolves to an int.
e
test2<Int>()
that is legal to write, and your default cannot work
p
The edge case should work just like when calling the function directly with those those two parameters. So it is valid and a, b, and return resolve to Any.
but if I don't provide a default value, test1<Int>("world") is also not legal. So not sure why test2<Int>() is expected to be legal.
Valid point if it becomes difficult to understand it should not be added. The real use case I encountered is with default implementations in constructors, but that is perhaps not very common. P.S Just quickly checked and indeed Scala 3 does support this ;)