调用! (bang)右操作数的方法

时间:2016-07-04 18:23:06

标签: scala

我能够定义一个名为的前缀运算符!对于没有参数的我的类型,我也可以使用以下代码调用!:右操作数上的方法:

class Cool {
    private var counter = 0

    def unary_!(): Unit = {
        counter += 1;
        println("Counter by ! is " + counter)
    }

    def !:(num: Int): Unit = {
        counter += num;
        println("Counter by !: is " + counter)
    }
}


object CoolApp extends App{
    val cool = new Cool
    ! cool // Prints "Counter by ! is 1"
    ! cool // Prints "Counter by ! is 2"
    12 !: cool // Prints "Counter by !: is 14"
}

然而,而不是!:方法我有兴趣!方法(适用于右操作数):

12 ! cool

知道我需要一个:在方法名称末尾将它应用到右操作数是有解决方案所以我可以拥有!代替 !: ?

总之,我希望在使用时增加一个计数器!没有左操作数,当有左操作数时,左操作数增加。

1 个答案:

答案 0 :(得分:4)

class Cool {
    private var counter = 0

    def unary_!(): Unit = {
        counter += 1;
        println("Counter by ! is " + counter)
    }

    def incrementBy(num: Int): Unit = {
        counter += num;
        println("Counter by incrementBy is " + counter)
    }
}


implicit class BangInt(val self: Int) extends AnyVal { 
    def ! (c: Cool): Unit = c incrementBy self 
}

您可以通过隐式转换将!方法添加到Int,这将按预期工作。

scala> val cool = new Cool
cool: Cool = Cool@d71adc2

scala> 21 ! cool
Counter by incrementBy is 21