Generics

ribrdb edited this page Jan 29, 2014 · 3 revisions

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.

Caveats

  • 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 ArrayList and add("a string") and add(Integer.class), it will infer as an ArrayList<Serializable> and that will be the return type of eg. get(0).
  • 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 extends Object.
  • 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.

Note that

  def first(foo:ArrayList):int
    foo.size
  end

does work as expected.

Future Plans

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.