Search code examples
javajrubydouble-brace-initialize

Double brace initialization in JRuby


I am trying out JRuby, and I was trying to figure out how to use Java's double brace initialization. However, it is not that apparent how the syntax would be.

To keep this example simple, the below Java code would create a list containing an element:

List<String> foo = new ArrayList<String>() {{
  add("bar");
}};


Is this possible in JRuby, and if so, how?

ArrayList.new {{}} doesn't make sense and results in the error: odd number list for Hash.puts ArrayList.new({{}}).


Solution

  • I don't think there is a way to do double curly brace initialization in JRuby. But for things like ArrayList Initialization JRuby offers shortcuts as in example below.

    Please check https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby for details.

    >> a = ArrayList.new [:a, :b, "c", "d"]
    #<Java::JavaUtil::ArrayList:0x65a953>
    >> a[0]
    :a
    >> a[1]
    :b
    >> a[2]
    "c"
    >> a[3]
    "d"
    >> a[4]
    nil