[Feature request][Idea] Generics with named arguments

Named arguments is an awesome feature that increases code readability. What about also specifying argument names for generic type arguments?

open class Something<X, Y>
class Another : Something<X = Int, Y = String>

fun <T> f() {}
fun g() { f<T = Int>() }

abstract class BaseListActivity<VIEWMODEL, MODEL>
class CatListActivity : BaseListActivity<VIEWMODEL = CatListViewModel, MODEL = Cat>()
//this ^^ is more readable than:
class CatListActivity : BaseListActivity<CatListViewModel, Cat>()
3 Likes

https://youtrack.jetbrains.com/issue/KT-1215

The linked issue suggests default types, but at least I find the naming aspect more useful.

Let’s say we had an interface:

interface Foo<Input, Thing, Output>

A usage would look like this:

class X : Foo<String, Int, Double>

With the current syntax it is impossible to see what String, Int, Double are. With the proposed syntax it would be obvious:

class X : Foo<Input = String, Thing = Int, Output = Double>

I doubt that default values would be that useful in practice.

A benefit of named parameters (with or without default values) would be that users would be encouraged to give meaningful names instead of T, U and the like. I think that this is a stupid convention of the time when there was mainly a single type parameter like in List<T>.

5 Likes

I tried to use more descriptive names in generic classes but, within the body of the class, I found that it was harder to see which names referred to standard types and which referred to generic type parameters of the class. Maybe this is just because of habits, and maybe the syntax coloring can actually compensate for that.

For methods, though, I find that this would make signatures longer, and maybe too long.

All that being said, allowing named type parameters doesn’t force anyone to use long names. Therefore, it cannot hurt anyone and I would be in favor of such a fetaure.

Syntax which you suggesting is very much looks like the default values for the formal parameters of the function. This is why @udalov suggested the link with default types.

Also location you suggesting is at the usage site and not definition site, so it cannot be default types.

BTW the same syntax is not supported for actual parameters for methods/functions. In case of variables I guess IntelliJ assumes meaningful names, but for literals it shows formal parameter name as a label. Why you are not suggesting this syntax for them also?

Instead of expending the language you can suggest JetBrains to show labels for types like they do for literals on call site of the method/function. This would encourage developers to use more meaningful names instead of more verbose text of the program.