17

渡されたevent.status場合にのみプロパティをテストする次のメソッドがあります。status

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && \\If status is not null: it.status == status
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}

私はそれがこのようにできると思ったが、うまくいかないようだ:

def findEvent(String desc, String status = null, Collection events) {
        return events.find {
            it.description == desc && (status != null ?: {it.status == status})
        }

        throw new Exception("Review Event Record Not Found: ${desc}")
}

これを行う方法はありますか?または、次のようなものに戻る必要がありますか。

if (status != null) {
    return events.find {
        it.description == desc && it.status == status
    }
} else if (status == null) {
    return events.find {
        it.description == desc
    }
}

ある種のベストプラクティスはありますか?

4

1 に答える 1

22

このままでは、その表現は理にかなっているとは思えません。

エルヴィスとは、「真実ならその価値を使い、そうでなければこの別のものを使う」という意味です。

あなたの「他のもの」はクロージャーであり、値はでありstatus != null、どちらもあなたが望むものではないようです。status null の場合、エルヴィスは と言いtrueます。そうでない場合は、追加の閉鎖層が得られます。

なぜ使用できないのですか:

(it.description == desc) && ((status == null) || (it.status == status))

それがうまくいかなかったとしても、必要なのは適切な値を返すためのクロージャだけですよね? 2 つの個別のfind呼び出しを作成する必要はありません。中間変数を使用するだけです。

于 2012-06-12T01:50:48.357 に答える