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
r
using the Java pattern that Kotlin was suppose to fix
I don't understand what you mean by this. Could you elaborate? Also, I'm not sure what you expect here. There are all sorts of edge cases here. for example, what about
Copy code
fun <T> test(a: T = "Hello", b: T = 7): T { ... }
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.
r
There are many edge cases to consider, not just that one. As another example, how would this resolve:
Copy code
fun <T> test(a: T = 9.0, b: T = a / 2.0): T { ... }

test("Help")
The issue is that it's not type safe (or at least not intuitively type safe). A default value should be of the type specified.
So not sure why test2<Int>() is expected to be legal.
Because
Int
is within the type bounds of the function. Default values are just that, defaults. They shouldn't change the specification of the function when used.
To be clear, I'm not arguing about whether this functionality is feasible. My issue is that it doesn't make any logical sense in any but the most trivial cases. I personally really don't want Kotlin to become Scala.
p
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 ;)
r
Yeah, the road to Scala is a slippery slope. It starts out so well intentioned, and before you know it... 🙂