Вопрос

I am starting work with grails.
I am quite confused in grails about using this << (bitwise left shift) operator.

I think it is use for assigning some value/object like
assignedTo << assignedValue

def outputBook = { output << Book.read(1) }

Is this the definite concept or not ?

Это было полезно?

Решение

Technically this is a Groovy and not Grails operator, and it's the additive operand. I seem to recall it delegates to the append method of the left hand. So for a collection it would add the element to the collection.

For example:

def things = ['one', 'two']
assert things.size() == 2
things << 'three'
assert things.size() == 3

The left shift << operator in Java is only used for bitwise operations. However, Groovy overrides this by delegating all operands to methods. This allows you implement your own. Take for instance the following use of plus:

class Baby {
  String name
  String toString(){"Baby: ${name}"}
}
class Person {
  String name
  def plus(Person o) {
    return new Baby(name: "${this.name} - ${o.name}")
  }
​}

def person1 = new Person(name: "Person 1")
def person2 = new Person(name: "Person 2")
assert "Baby: Person 1 - Person 2" == (person1 + person2)
​

Pretty Groovy eh?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top