Skip to content

Commit

Permalink
feat: do not check whether optional type parameters of classes can be…
Browse files Browse the repository at this point in the history
… inferred (#1090)

Closes #1084

### Summary of Changes

Optional type parameters of classes are now always allowed, even if they
can never be inferred from their usage in the constructor.

This is useful to initialize them to some default value upon
instantiation and override this value later, e.g. in return types of
functions. See #1084 for an example.
  • Loading branch information
lars-reimann authored Apr 23, 2024
1 parent 09faaf0 commit 31b8a28
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ export const typeParameterMustHaveSufficientContext = (node: SdsTypeParameter, a
}
/* c8 ignore stop */

// Classes without constructor can only be used as named types, where type arguments are manifest
if (isSdsClass(containingCallable) && !containingCallable.parameterList) {
// Optional type parameters of classes get initialized to their default value if there is insufficient context in
// the constructor. Elsewhere, the class might be used as a named type, where type arguments are manifest, so having
// the type parameter is beneficial. This is not the case for functions, where type parameters only get inferred.
//
// Classes without constructor can only be used as named types, where type arguments are manifest.
if (isSdsClass(containingCallable) && (TypeParameter.isOptional(node) || !containingCallable.parameterList)) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class MyClass8<»T«>(param: () -> (r: (p: T) -> ()))
class MyClass9<»T«>(param: union<T>)
// $TEST$ error "Insufficient context to infer this type parameter."
class MyClass10<»T«>(param: union<T, Int>)
// $TEST$ no error "Insufficient context to infer this type parameter."
class MyClass11<»T« = Int>()

// $TEST$ error "Insufficient context to infer this type parameter."
fun myFunction1<»T« sub Int>()
Expand All @@ -39,3 +41,5 @@ fun myFunction6<»T«>(param: () -> (r: (p: T) -> ()))
fun myFunction7<»T«>(param: union<T>)
// $TEST$ error "Insufficient context to infer this type parameter."
fun myFunction8<»T«>(param: union<T, Int>)
// $TEST$ error "Insufficient context to infer this type parameter."
fun myFunction9<»T« = Int>()

0 comments on commit 31b8a28

Please sign in to comment.