Duck typing is often used in dynamic languages - http://en.wikipedia.org/wiki/Duck_typing. You can do this with scala in a perfectly type safe way using structural types.

You can either define the signature in the method signature (as shown in the manual), but a better way for more complex structures is to use a type alias:

object structurals {
  type YourType = { def method():Something; def another():Something }
  //you can have more type aliases here if needed
}

You then import it into any scope that needs these types:

import structurals._

Then you use it like so :

  def yourMethod(f: YourType) = println(f.method())

Now you can pass around any objects that match the structural type, yet your structural definitions are nicely reusable.

 
patterns/duck-typing-done-right.txt · Last modified: 2007/10/14 05:45 by michaelneale
 
Recent changes RSS feed Valid XHTML 1.0 Driven by DokuWiki