1

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({{}}).

Community
  • 1
  • 1
whirlwin
  • 16,044
  • 17
  • 67
  • 98
  • The [double brace initialization](http://c2.com/cgi/wiki?DoubleBraceInitialization) is just creating an anonymous inner subclass of `ArrayList` here. – obataku Sep 04 '12 at 01:24
  • 3
    Just because JRuby runs on the JVM doesn't mean it brings Java syntax to Ruby. – echristopherson Sep 04 '12 at 06:00
  • @echristopherson I have updated the actual question so it doesn't sound too "demanding". – whirlwin Sep 04 '12 at 16:54
  • 1
    The double-brace initialization is a hacky workaround because Java doesn't have literal constructors like Ruby has. Why on earth wouldn't you just want to use the Ruby syntax? – Mark Thomas Sep 04 '12 at 16:55
  • @MarkThomas In my opinion, I think it's cleaner to have the logic which has to do with initialization enclosed inside the braces. – whirlwin Sep 04 '12 at 17:12
  • @whirlwin Cleaner than the alternate Java syntax, because Java lacks literal constructors for basic types. But not cleaner than Ruby syntax. – Mark Thomas Sep 04 '12 at 17:19
  • @MarkThomas Yes, but can I pass a block to ArrayList's constructur at all? – whirlwin Sep 04 '12 at 17:29
  • @MarkThomas NVM, I figured it out by passing a Ruby Array into ArrayList's constructor. `ArrayList.new Array.new(10) { 42 }`. :) – whirlwin Sep 04 '12 at 17:38

2 Answers2

2

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
arkadiy kraportov
  • 3,679
  • 4
  • 33
  • 42
1

While not a direct answer to the question, am I adding this because this is a convenient way of having some logic determine what each element will be. This is done passing a Ruby Array into ArrayList's constructor.

ArrayList.new Array(10) {|i| i*i}

Thanks to Mark Thomas for helping me think. :)

Community
  • 1
  • 1
whirlwin
  • 16,044
  • 17
  • 67
  • 98