What is the purpose of “<<” (double less than) in groovy

后端 未结 2 1937
暗喜
暗喜 2020-12-06 05:54

I saw in some of the code which I am unable to understand the purpose of << like in the following sample code

def renderFiles(args) {
   def model = []         


        
2条回答
  •  鱼传尺愫
    2020-12-06 06:17

    This is a leftShift operator. In groovy operator overloading is implemented, see here and the new docs for reference . In this particular case adding an element to list operation is overloaded.

    Instead of:

    model.add(createModel(fileArgs.id,fileArgs.path,fileArgs.ext))

    You can simply write:

    model << createModel(fileArgs.id,fileArgs.path,fileArgs.ext)

    It's a kind of a shorthand. There are also other operators overridden for List class, e.g. plus(), minus(). See here.

提交回复
热议问题