wureka
wureka

Reputation: 865

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.

Upvotes: 3

Views: 1507

Answers (1)

Opal
Opal

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

Related Questions