Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Add retry() into Java Runnable class

  • It extends java.lang.Runnable by adding a new method i.e. retry
  • Within the retry extension method. Runable will be executed by calling its run method.
  • If any exception ever happens, retry again till the decrement of counter hits 0.
  • The this in the retry extension method is referring to the receiver, which in this case is an instance of Runnable.
fun Runnable.retry(numberOfRetries: UInt) {
    try {
        this.run();
    } catch (e: Exception) {
        if (numberOfRetries.equals(0u)) {
            return
        }
        val resultNumberOfRetries = numberOfRetries - 1u
        retry(numberOfRetries = resultNumberOfRetries);
    }
}
@Test
fun contextLoads() {
	val action = Mockito.mock(Runnable::class.java)
	action.retry(3u)
	verify(action, atLeastOnce()).run()
}

Reference

Extension Methods in C#

Last modified: June 1, 2020

Author