[Feature request][Idea] Generics with named arguments

#1

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>()
2 Likes
#2

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

#3

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
#4

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.