示例扩展 Java 7 Path 类

扩展方法的常见用例是改进现有 API。以下是将 existnotExistsdeleteRecursively 添加到 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()