A common use case for extension methods is to improve an existing API. Here are examples of adding exist
, notExists
and deleteRecursively
to the Java 7+ Path
class:
fun Path.exists(): Boolean = Files.exists(this)
fun Path.notExists(): Boolean = !this.exists()
fun Path.deleteRecursively(): Boolean = this.toFile().deleteRecursively()
Which can now be invoked in this example:
val dir = Paths.get(dirName)
if (dir.exists()) dir.deleteRecursively()