Clone this wiki locally
Mirah has support for using generics. That is, you can use classes, like the Collections framework, that have generics, and Mirah will infer the types correctly. There is no support yet for defining generic classes in Mirah.
- The value of a type variable will be the most specific common parent of the types it is matched to in method parameters (not return types). If I have an
add(Integer.class), it will infer as an
ArrayList<Serializable>and that will be the return type of eg.
- If you do not constrain a type variable at all, it defaults to
Object. Or, more precisely, it defaults to whatever the bounds given on the generic class are, which default to
- The above two points can affect the public API of a Mirah class that uses generics internally. You can control the inferred type by judicious use of casting. There is currently no syntax to explicitly set the type variables; we were considering the syntax
ArrayList.new<String>()but are open to suggestions. That may be added as part of my work on defining generic classes in Mirah, but we've proven that we can infer the type variables without having them specified anywhere.
- Methods that have their own type parameters are not supported. In particular, this means you can't use
Collections.sort()and the like.
Mirah methods and generics
Mirah methods expecting or returning generic types need to be careful. The following is an inference error:
class A ... def first(foo:ArrayList):String foo.get(0) end end
Because the compiler can't guarantee the type of the provided
ArrayList when compiling that method, even if you pass it an
ArrayList<String>. As part of defining generics in Mirah, the ability to write that method as
def first(foo:ArrayList<String>):String will be added.
def first(foo:ArrayList):int foo.size end
does work as expected.
In rough order of highest to lowest priority, I'm intending to add:
- Parsing of generic types in Mirah method signatures, as mentioned in the above section.
- Defining generic classes in Mirah.