Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the groovy << operator mean in this context?

Tags:

groovy

In a groovy tutorial, I encountered the following code:

class DateTagLib {   def thisYear = {     out << Calendar.getInstance().get(Calendar.YEAR)   } } 

I don't know what the << means, and I'm having no luck with google.

Edit: I now know that << sometimes is a bit shift. But what does it mean here?

like image 515
Eric Wilson Avatar asked Sep 04 '10 06:09

Eric Wilson


People also ask

What is Groovy operator?

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Groovy has the following types of operators − Arithmetic operators. Relational operators.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What does >> mean in Spock?

The right-shift ( >> ) operator defines the return value or behavior of a stubbed method.


2 Answers

In groovy, the bitwise operators can be overridden with the leftShift (<<) and rightShift (>>) methods defined on the class. It's idiomatic groovy to use the leftShift method for append actions on strings, buffers, streams, arrays, etc and thats what you're seeing here.

For example:

  • The overloaded leftShift methods on OutputStream which are used to append bytes, an InputStream, or an Object to the stream.
  • List, which also uses it as an append

You are looking at a grails tag lib, so out represents the page that's being rendered. The results of this taglib will be added to the output buffer that will be rendered to the client.

like image 102
Ted Naleid Avatar answered Sep 24 '22 18:09

Ted Naleid


Assuming that out is System.out the << operator writes to out in this case. The idiom to overload << for output (writing to a stream) and >> for input (reading from a stream) comes from C++. When the stdio libraries (istream ostream etc.) got defined, the idea was born to use left shift and right shift for output and input.

like image 42
Angel O'Sphere Avatar answered Sep 21 '22 18:09

Angel O'Sphere