【问题标题】:Simplest way to implement one-method interfaces in Groovy?在 Groovy 中实现单方法接口的最简单方法是什么?
【发布时间】:2023-03-20 23:59:01
【问题描述】:

在 Groovy 中实现单方法接口的最简单方法是什么?

比如RunnableFileFilter

例如,列出我写的类似 java 的文件:

// works Java-like
new File(".").listFiles(new FileFilter() {
    @Override
    boolean accept(File file) {
        !file.isDirectory()
    }
}).each { println it.absolutePath }

但是闭包式不起作用

// does not work
new File(".").listFiles({file -> !file.isDirectory()}).each { println it.absolutePath }

是否可以使用闭包之类的来实现它?

【问题讨论】:

    标签: groovy closures


    【解决方案1】:

    在这个特定示例中,以下代码应该可以工作:

    return [downloadFolder: downloadFolder.listFiles({ file ->
               return !file.isDirectory()
           })]
    

    基本上可以使用Map 实现接口。

    编辑 在这个特定的例子中,它应该是:

    new File(".").listFiles({file -> !file.isDirectory()} as FileFilter).each { println it.absolutePath }
    

    【讨论】:

    • 它怎么知道{file -> !file.isDirectory()}应该实现即FileFilter?它在这里推断类型吗?
    • 它将动态运行。
    • 如果我的类型不明确怎么办,比如FileFilterFileFilter2 使用相同的代码
    • 你有例子吗?在这种情况下可以使用as关键字。
    • 不工作顺便说一句。说不能区分FileFilterFilenameFilter
    猜你喜欢
    • 2018-02-09
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多