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 {
    } catch (e: Exception) {
        if (numberOfRetries.equals(0u)) {
        val resultNumberOfRetries = numberOfRetries - 1u
        retry(numberOfRetries = resultNumberOfRetries);
fun contextLoads() {
	val action = Mockito.mock(Runnable::class.java)
	verify(action, atLeastOnce()).run()


Extension Methods in C#

Last modified: June 1, 2020