Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy dynamically add method with argument

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.

like image 699
wureka Avatar asked Dec 12 '25 16:12

wureka


1 Answers

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 ;)
like image 77
Opal Avatar answered Dec 16 '25 21:12

Opal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!