Mid() Function Error


#1

According to the wiki, mid(‘Hello World’,2) should output ‘llo World.’ It instead produces an error

groovy.lang.MissingMethodException: No signature of method:
java.lang.String.substring() is applicable for argument types:
(java.lang.Integer, null) values: [2, null]Possible solutions:
substring(int), substring(int, int), toString(), toString(), toString().


#2

Looks like the wiki might be wrong here and that the third parameter is not optional. (I personally have used only the 3-parameter version of this function in my pistons). You can feed it a really large number though and it still works:

(expression) mid("Hello World", 2, 9999999999) »»» (string) llo World

@ady624: is the wiki wrong or did this work at one time and no longer does?


#3

I think that mid/substring should fixed in webCoRE since being able to omit the second parameter is expected behavior for standard implementations of this function.

It looks like the intention was to use the default behavior of String.substring when the third parameter is omitted, but it’s not done in a supported way. I would advise changing this line in the webCoRE Piston SmartApp from

result = value.substring(start, count == null ? null : start + count)

to

        if (count == null) {
	        result = value.substring(start)
        } else {
	        result = value.substring(start, start + count)
        }

You could leave it as a one-liner and calculate the correct length to use instead of null, but I like this approach since it leverages the existing behavior of String.substring. Otherwise you could calculate the proper count by including a null check in the preceding line:

        if (count == null || count > value.size() - start) count = value.size() - start
        result = value.substring(start, start + count)

#4

wouldnt it be simpler to move up the tenary operator and still keep it to a line:

result = count == null ? value.substring(start) : value.substring(start, start + count)​


#5

Version 0.2.0fa fixes this - please update your code with the latest version.


#6

Does the wiki need to be updated?


#7

no, the function now matches the wiki.