ConsString can cause some hard-to-find bugs when interacting with Java classes.

Consider this code:

  var map = new java.util.HashMap

  var prefix = 'a'
  var key = prefix + 'b'

  map.put(key, 'hello')

  print(map.get(key) + '\n')
  print(map.get('ab') + '\n')

It will output 'hello' and then 'null'. The reason is that key is a ConsString. See for yourself:

  for (var i = map.keySet().iterator(); i.hasNext(); ) {
    print(i.next().getClass() + '\n')
  }

This can cause some very hard-to-find bugs. I know too well. :). I'm not sure how best to deal with it, but here are some suggestions.

1. Document it in the user guide, possibly with the simple example I gave above. I expect that many of these bugs will happen when dealing with generic classes, such as those in java.util. The workaround for the example above:

  var key = String(prefix + 'b')

But that's hardly intuitively necessary.

2. It may be a good idea for Nashorn to always coerce ConsString into String when interacting with Java, even if the method signature expects an Object.

The one downside I can think of is that it will make it impossible to offer special handling for ConsString in Java classes. This would seem, however, to be quite a rare usage and may not be worth the potential for awful bugs.

What do you think?


Reply via email to