You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This change implements lower bound constraints for generic type
parameters in RBS, allowing declarations like `[T > SomeType]`.
The implementation includes:
- Parser and lexer modifications to handle ">" token in type params
- Relevant changes to the Ruby API, like Locator and Validator
- Schema updates to typeParam.json
- Documentation updates
| `<`_type_ (The generics parameter has an upper bound)
768
+
| '>' _type_ (The generics parameter has a lower bound)
768
769
769
770
_default-type_ ::= (No default type)
770
771
| `=`_type_ (The generics parameter has default type)
@@ -834,7 +835,7 @@ class PrettyPrint[T < _Output]
834
835
end
835
836
```
836
837
837
-
If a type parameter has an upper bound, the type parameter must be instantiated with types that is a subtype of the upper bound.
838
+
If a type parameter has an upper bound, the type parameter must be instantiated with types that are a subtype of the upper bound.
838
839
839
840
```rbs
840
841
type str_printer = PrettyPrint[String] # OK
@@ -854,6 +855,21 @@ type foo = _Foo # equivalent to _Foo[untyped]
854
855
type bar = _Bar[String] # equivalent to _Bar[String, untyped]
855
856
```
856
857
858
+
You can also specify the _lower bound_ of the type parameter using `>`. This constrains the type parameter to be a supertype of the specified bound. Both an upper and a lower bound can be specified for the same type parameter.
859
+
860
+
```rbs
861
+
class FlexibleProcessor[T > Integer < Numeric]
862
+
# This class processes types T that are supertypes of Integer but also subtypes of Numeric.
863
+
# This includes Integer, Rational, Complex, Float, and Numeric itself.
864
+
def calculate: (T) -> T
865
+
end
866
+
867
+
type int_processor = FlexibleProcessor[Integer] # OK (Integer > Integer and Integer < Numeric)
868
+
type num_processor = FlexibleProcessor[Numeric] # OK (Numeric > Integer and Numeric < Numeric)
869
+
type obj_processor = FlexibleProcessor[Object] # Type error (Object is not < Numeric)
870
+
type str_processor = FlexibleProcessor[String] # Type error (String is not > Integer)
871
+
```
872
+
857
873
Type parameters with default types cannot appear before type parameters without default types. The generic method type parameters cannot have the default types.
0 commit comments