記住方法

由於只需新增 @Memoized 註釋即可將 Groovy 2.2 groovy.transform.Memoized 註釋新增到方便的 memoize 方法中:

import groovy.transform.Memoized

class Calculator {
    int sum(int x, int y){
        println "sum ${x} + ${y}"
        return x+y
    }   
    
    @Memoized
    int sumMemoized(int x, int y){
        println "sumMemoized ${x} + ${y}"
        return x+y
    }
}

def calc = new Calculator()

// without @Memoized, sum() method is called twice
calc.sum(3,4)
calc.sum(3,4)
// prints
// sum 3 + 4
// sum 3 + 4

// with @Memoized annotation
calc.sumMemoized(3,4)
calc.sumMemoized(3,4)
// prints
// sumMemoized 3 + 4