Groovy Map as Interface method in JRuby


/ Published in: Ruby
Save to your folder(s)

Groovy has the as keyword which enables the implementation of a Java interface by using the as keyword, its quite easy to mimic this in JRuby.


Copy this code and paste it in your HTML
  1. module InvokableHash
  2. def as(java_ifc)
  3. # Each method will create a key in the hash which points to a block
  4. # which is called
  5. java_ifc.impl {|name, *args| self[name].call(*args)}
  6. end
  7. end
  8.  
  9. class Hash
  10. include InvokableHash
  11. end
  12.  
  13. impl = {
  14. :i => 10,
  15. :hasNext => proc { impl[:i] > 0 },
  16. :next => proc { impl[:i] -= 1 }
  17. }
  18.  
  19. iter = impl.as java.util.Iterator
  20. while (iter.hasNext)
  21. puts iter.next
  22. end

URL: http://blog.headius.com/2007/12/groovy-in-ruby-implement-interface-with.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.