【问题标题】:Groovy equivalent for Scala implicit parametersScala 隐式参数的 Groovy 等效项
【发布时间】:2012-11-14 11:54:49
【问题描述】:

是否有一些 Groovy 替代方法来表达如下内容:

def doSomethingWith(implicit i:Int) = println ("Got "+i)
implicit var x = 5

doSomethingWith(6)  // Got 6
doSomethingWith     // Got 5

x = 0
doSomethingWith     // Got 0

更新:在此处查看后续问题:Groovy equivalent for Scala implicit parameters - extended

【问题讨论】:

    标签: scala groovy implicits


    【解决方案1】:

    您可以使用带有默认参数的闭包:

    doSomethingWith = { i = value -> println "Got $i" }
    value = 5
    
    doSomethingWith(6)  // Got 6
    doSomethingWith()   // Got 5
    
    value = 0
    doSomethingWith()   // Got 0
    

    【讨论】:

    • 答案很合适,但它有什么相似之处?在 Groovy 示例中,value 变量和value 默认参数值必须相同。在 Scala 中x 中,局部变量和i 可以有不同的名称并定义在不同的位置。
    【解决方案2】:

    这就是我在 Groovy 中做隐式的方式

    @Test
    def void customString() {
        println "Welcome implicits world in groovy".upperCaseNoSpace
        println "Welcome implicits world in groovy".removeSpaces
    
    }
    
    static {
        String.metaClass.getUpperCaseNoSpace = {
            delegate.toUpperCase().replace(" ", "_")
        }
    
        String.metaClass.getRemoveSpaces = {
            delegate.replace(" ", "")
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-03
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      相关资源
      最近更新 更多