user63898
user63898

Reputation: 30895

groovy can Normal ternary operator preform more then one oparation?

i have this Normal ternary operator but i like it to do more then 1 operation if false
for example :

def xxStr = x.x.1.1
    def ver = 0
    xxStr = (xxStr.contains('foo')) ? xxStr.replace('-foo','').tokenize('.') : xxStr.tokenize('.') && ver = xxStr.pop()

of coruse this not working as xxStr.tokenize('.') && ver = xxStr.pop()
is not ligal , but is there any elegant way to do this ?

Upvotes: 3

Views: 9592

Answers (3)

tim_yates
tim_yates

Reputation: 171084

Another option is to use with as in:

xxStr = xxStr.contains('foo') ? xxStr.replace('-foo','').tokenize('.') : xxStr.tokenize('.').with { pop() }

Upvotes: 2

Mark Bramnik
Mark Bramnik

Reputation: 42451

You'll need a block of code that can be executed at once.

One option (obviously) is to call a function that will execute all the operations:

def func() {
  println("no")
  println("definitely not")
}
(10 > 20) ? println ("yes") : func()

Another option is using closure:

​(10 > 20) ? println("yes") :  {​​​​​​​println("no"); println ("definitely not")​​​​​​​​​​​​}.call()

Both versions print:

no
definitely not

Upvotes: 0

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

The ternary operator assigns value to a variable, thus you can't call assignment expression here. But there are more issues with the code you have presented. For instance:

xxStr.tokenize('.') && ver = xxStr.pop()

Expecting that xxStr after calling xxStr.tokenize('.') is a list is an misconception. The xxStr in this expression remains a String thus calling pop on it will throw MissingMethodException.

Forcing your code to be a one-liner does not mean you are using an elegant solution. In this case, I would say that it is the opposite. Also, you are using def in a dynamic context (you change the type from String to List). It is not prohibited, but in most cases, it only introduces confusion. It makes your code harder to understand and reason about.

I would strongly suggest diving the code into two separate sections: one responsible for tokenizing a string to an array, and second one responsible for popping the version. It makes your code more explicit and easier to understand. If there was a built-in easy-to-read solution in Groovy, you could consider using it. But adding this unnecessary level of abstraction to such a simple use case makes a very little sense.

Upvotes: 0

Related Questions