扩展方法的常见用例是改进现有的API。下面是添加的例子exist,notExists并deleteRecursively到Java 7+Path类:
fun Path.exists(): Boolean = Files.exists(this) fun Path.notExists(): Boolean = !this.exists() fun Path.deleteRecursively(): Boolean = this.toFile().deleteRecursively()
现在可以在此示例中调用:
val dir = Paths.get(dirName) if (dir.exists()) dir.deleteRecursively()