如何用Groovy代替嵌套if

时间:2018-08-17 01:50:12

标签: groovy builder

我必须构建和标识,它取决于不同的参数。如果其中一些不是null,则必须根据参数在这些值后面附加一些联合符号,例如“〜”或某些前缀。

这是我在以下情况下使用嵌套的实现:

    def buildUID( def sportId, def leagueId, def groupId, def eventId, def teamId, def competitionId )
{
    def delimiter = "~"
    def returnString = ""
    sportId = sportId + ''
    leagueId = leagueId + ''
    groupId = leagueId + ''
    teamId = teamId + ''
    eventId = eventId + ''
    competitionId = competitionId + ''
    if ( this.commonPresenter.isNotNull( sportId ) )
    {
        returnString = "s:" + sportId

        if ( this.commonPresenter.isNotNull( leagueId ) )
        {
            if ( this.commonPresenter.isNull( teamId ) )
            {
                if ( this.commonPresenter.isNull( groupId ) )
                {
                    if ( this.commonPresenter.isNotNull( eventId ) )
                    {
                        returnString = returnString + delimiter + "l:" + leagueId + delimiter + "e:" + eventId
                    }
                    else if ( this.commonPresenter.isNotNull( competitionId ) )
                    {
                        returnString = returnString + delimiter + "l:" + leagueId + delimiter + "c:" + competitionId
                    }
                    else
                    {
                        returnString = returnString + delimiter + "l:" + leagueId
                    }
                }
                else
                {
                    returnString = returnString + delimiter + "l:" + leagueId + delimiter + "g:" + groupId
                }
            }
            else if ( sportId == "600" )
            {
                returnString = returnString + delimiter + "t:" + teamId
            }
            else
            {
                returnString = returnString + delimiter + "l:" + leagueId + delimiter + "t:" + teamId
            }
        }
        else if ( ( this.commonPresenter.isNull( leagueId ) ) && sportId == "600" && this.commonPresenter.isNotNull( teamId ) )
        {
            returnString = returnString + delimiter + "t:" + teamId
        }
    }
    return returnString + ''
}

谢谢。

1 个答案:

答案 0 :(得分:0)

一个想法:使用地图和函数处理集合

def ret = [
    sportId:11,
    leagueId:22, 
    groupId:null, 
    eventId:44, 
    teamId:'z', 
    competitionId:66
].findAll{it.value!=null}.collect{it.key[0]+':'+it.value}.join('~')

返回

s:11~l:22~e:44~t:z~c:66