Groovy变量作用域

Groovy变量作用域

Groovy变量作用域有两个,要想成为全局作用域,需要用@Field标示

import groovy.transform.Field

@Field File configFile
@Field final KEY_CONFIG_NAME = 'pitaya_component.config'
@Field final KEY_MAIN_HOST = 'mainHost'
@Field final KEY_SUB_HOST = 'subHost'

configFile = new File(getRootDir(), KEY_CONFIG_NAME)
if (configFile.exists()) {
    configFile.delete()
}

void mainHostInclude(String[] projectPaths) {
    include(projectPaths)
    projectPaths.each { projectName ->
        configFile.append(KEY_MAIN_HOST + projectName + "\n")
    }
}

mainHostInclude ':app'

Groovy 语法each中用return

    private boolean isNotHost2(String projectName) {
        mComponentConfigMap.values().forEach({ contentList ->
            contentList.forEach({ line ->
                System.out.println(line + " is  " + false)
                return false
            })
        })

        System.out.println(projectName + " is  " + true)
        return true
    }

输入结果

subHost:setting is  false
subHost:printer is  false
mainHost:app is  false
setting is  true

不合常理,return了,咱么for循环还在继续。我看看如下forEach的源码,原理闭包是一个Consumer类,在Consumer类中的方法调用return,只是退出了Consumer。外层for没有退出。那我们该如何整体退出呢?
自己改写为 for方式

    default void forEach(Consumer action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
``

你可能感兴趣的:(Groovy变量作用域)