Gradle/Groovy syntax confusion

自古美人都是妖i 提交于 2020-06-23 04:45:47

问题


Can anyone explain/comment on this fraction of Groovy code?

task copyImageFolders(type: Copy) {
    from('images') {
        include '*.jpg'
        into 'jpeg'
    }

    from('images') {
        include '*.gif'
        into 'gif'
    }

    into 'build'
}

More specifically about the from method. Is this the

from(sourcePaths)

or the

from(sourcePath, configureAction)

If its the one with the 2 arguments, why it’s written this way and not something like:

 from('images', {
     include '*.jpg'
     into 'jpeg'
 })

回答1:


The short answer is it's calling from(sourcePath, configureAction).

Groovy has optional brackets in a number of cases and accepts the last parameter (if it's a closure) outside of brackets and in this case that's the closure that you're passing to from().

This is a good blog post explaining the different ways a closure can be passed to a method in Groovy if you want more examples and this offers more examples of optional brackets in general.




回答2:


It's Syntactic Sugar, to make things easier to read (very useful for Gradle configuration)

In this case it's all about parentheses.

When a closure is the last parameter of a method call, like when using Groovy’s each{} iteration mechanism, you can put the closure outside the closing parentheses, and even omit the parentheses:

list.each( { println it } )
list.each(){ println it }
list.each  { println it }

In your case, everything below is working fine :

from('images', {
    include '*.jpg'
    into 'jpeg'
})

from('images') {
    include '*.gif'
    into 'gif'
}

from 'images', {
    include '*.gif'
    into 'gif'
}


来源:https://stackoverflow.com/questions/49996424/gradle-groovy-syntax-confusion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!