Reputation: 865
I want add a method "toFormatString(fmt)" to the existed class java.util.Date. My code is below:
Date.metaClass.toFormatString(String fmt) = {
SimpleDateFormat sdf = new SimpleDateFormat(fmt)
return sdf.format(delegate)
}
However, Intellij gives me an error: Invalid value to assign to.
Upvotes: 3
Views: 1507
Reputation: 84864
It should be:
import java.text.SimpleDateFormat
Date.metaClass.toFormatString = { String fmt ->
SimpleDateFormat sdf = new SimpleDateFormat(fmt)
return sdf.format(delegate)
}
assert new Date().toFormatString('yyyy') == '2015' //will work in 2015 only ;)
Upvotes: 5