Implicit generics with type narrowing #8079
Unanswered
simon-curtis
asked this question in
Language Ideas
Replies: 2 comments
-
Cecil Phillips tweet here outlines unnecessary generics in the signature when you are trying to restrict a generic type. class Customer : Entity;
abstract class MyService<T> where T : Entity;
class CustomerService : MyService<T>;
static class MyProvider
{
public static TService GetService<TService>()
where TService : MyService<U>
where U : Entity
{
}
}
// In this case `U` would be undefined, and you would have to declare it in the instance:
MyProvider.GetService<CustomerService, Customer>(); We could do better with static class MyProvider
{
public static TService GetService<TService, impl TEntity>()
where TService : MyService<TEntity>
// TEntity is automatically `where TEntity : Entity` since that is the constraint on MyService
{
}
}
// Customer is implied here
MyProvider.GetService<CustomerService>(); |
Beta Was this translation helpful? Give feedback.
0 replies
-
See also: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
A big frustration I have when declaring objects with generic type arguments is where it is a requirement of the compiler to specify all the generic types even if they can only be one value. Take this model structure:
Currently in order for me to constrain
TUser
to theIIdentifiableEntity<TKey>
I've also got to specifyTKey
but because of the type a narrowing it can only beint
If the compiler is able to enforce this constraint, it must already be identifying the type of
TKey
. My proposal is that a keyword (maybeimpl
) is introduced to tell the compiler that the key should be inferred based on the type narrowing done by a previous generic type argument.This would allow the user to override if they want to, for example
TKey
is an interface and you want to specify a concrete implementation (can't think of a code example where you would want this). This pattern would only apply to cases where theTKey
is narrowed to a single type, so issues with finding a base type would not be an issue.I come across this issue a fair amount and have spoken to people who share my opinion on it. I think it would be a nice QoL for both authors and consumers. I think I have seen instances where people use a non-generic base class because they don't know the TKey at compile time and it forces you to use an
object
and case it at runtime.Beta Was this translation helpful? Give feedback.
All reactions