Operators

Groovy keeps the operators of Java and adds a set that removes a null check or a loop from the page. Every line below is one of them, in the smallest program that shows what it does.

Safe navigation and Elvis

nullsafe.groovy

def person = [name: 'Ada', city: null] println person.name?.toUpperCase() println person.city?.toUpperCase() def nickname = person.nickname ?: 'no nickname' println nickname def city = person.city ?: 'unknown' println city

groovy nullsafe.groovy

ADA
null
no nickname
unknown

?. returns null instead of throwing when the receiver is null, so a chain of calls needs one question mark per step that may be missing. ?: is the Elvis operator: the value on the left when it is true, the right side otherwise.

Spread and range

spread.groovy

def words = ['ada', 'grace', 'barbara'] println words*.length() println words*.toUpperCase() def range = 1..5 println range println range.sum() println(10..<13) println range.collect { it * 2 }

groovy spread.groovy

[3, 5, 7]
[ADA, GRACE, BARBARA]
1..5
15
10..<13
[2, 4, 6, 8, 10]

*. calls the method on every element and collects the results, which is collect in one character. A range is a List with a lazy cousin: .. includes the last value, ..< stops before it.

The spaceship and the pattern operators

regex.groovy

def one = 1 def two = 2 def a = 'a' def b = 'b' def listA = [1, 2] def listB = [1, 2] println(one <=> two) println(listA.size() <=> listB.size()) println(b <=> a) def text = 'order 42 shipped' println(text =~ /\d+/) println(text ==~ /\d+/) println((text =~ /\d+/)[0]) println(text.replaceAll(/\d+/, '43')) println(42 in 1..100)

groovy regex.groovy

-1
0
1
java.util.regex.Matcher[pattern=\d+ region=0,16 lastmatch=]
false
42
order 43 shipped
true

<=> answers -1, 0 or 1 and is what a comparator needs. =~ finds a pattern anywhere in the text and returns a matcher whose truth is whether it found something; ==~ asks whether the whole text matches. in asks a range or a collection for membership.

Assignment and the null-safe index

assign.groovy

def list = [1, 2, 3] list << 4 list += 5 println list println list[-1] println list[1..2] def map = [:] map.name = 'Ada' map['age'] = 36 println map

groovy assign.groovy

[1, 2, 3, 4, 5]
5
[2, 3]
[name:Ada, age:36]

<< appends to a list, += builds a new one for the assignment, a negative index counts from the end, and a range as an index is a slice. An empty map literal is [:], and the two ways of writing a key produce the same map.

Related

Автор статьи: Arthur Isaev