Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow referring to the type parameters of a generic class outside of the class scope #3540

Closed
LongCatIsLooong opened this issue Jan 5, 2024 · 1 comment
Labels
request Requests to resolve a particular developer problem

Comments

@LongCatIsLooong
Copy link

I have the following interface:

abstract class A<B extends Object> { }

I would like to be able to write:

class C implements A<int> { }

T.B someFunction<T extends A<num>>() { ... }

// `T` doesn't actually appear in the signature so it cannot be inferred.
final returnValue = someFunction<C>()

However currently one has to specify both type parameters, which makes calling the someFunction API a bit clumsy:

// `B` is used as the return type but otherwise redundant. 
B someFunction<T extends A<B>, B extends num>() { ... }

final returnValue = someFunction<C, int>();
// It gets worse when `A` has more than one type parameters, with long class names:
final returnValue' = someFunction'<C, SophisticatedClassName1, SophisticatedClassName2>();

Proposal

Exposing the names of generic classes' type parameters, maybe as associated types:

abstract class A<B extends Object> {
  typedef B' = B;
}

T.B' someFunction<T extends A<num>>() { ... }
@LongCatIsLooong LongCatIsLooong added the request Requests to resolve a particular developer problem label Jan 5, 2024
@lrhn
Copy link
Member

lrhn commented Jan 5, 2024

I'd suggest using type patterns (#170), preferably with a more actual-pattern-like syntax, to extract the type parameter of a generic type.

R someFunction<T extends A<final R>>() { ... }

It can use either the runtime type of the type T, and extract R on every runtime invocation, or use the static type of a single invocation point extracted (inferred) at compile-time (I'd prefer the former, that's what's currently impossible to do otherwise.)

I think this might just be a duplicate of #170, with slightly different syntax.

@LongCatIsLooong LongCatIsLooong closed this as not planned Won't fix, can't repro, duplicate, stale Jan 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

2 participants