Groovy语法学习(五)运算符重载

groovy同样具有运算符重载的功能,其实运算符也是调用类中的具体方法,使用运算符看起来更加简洁,容易理解。
简单重载一个减法

class Money{
    def number

    def  minus(o){
        if(o instanceof Money){
            number-=o.number
        }else if(o instanceof Number){
            number-=o
        }
        this
    }


    @Override
    public String toString() {
        return "Money{" +
                "number=" + number +
                '}';
    }
}

def m=new Money(number: 100)
def b=new Money(number: 50)

println m-b
println m-30

结果:

Money{number=50}
Money{number=20}

下面附上操作符重载的表,大家可以自行查看,原博客地址https://www.cnblogs.com/rollenholt/archive/2013/10/02/3349047.html

下面的表格描述了groovy中的操作符所映射到的方法:

Operator

Method

a + b

a.plus(b)

a – b

a.minus(b)

a * b

a.multiply(b)

a ** b

a.power(b)

a / b

a.div(b)

a % b

a.mod(b)

a | b

a.or(b)

a & b

a.and(b)

a ^ b

a.xor(b)

a++ or ++a

a.next()

a– or –a

a.previous()

a[b]

a.getAt(b)

a[b] = c

a.putAt(b, c)

a << b

a.leftShift(b)

a >> b

a.rightShift(b)

switch(a) { case(b) : }

b.isCase(a)

~a

a.bitwiseNegate()

-a

a.negative()

+a

a.positive()

另外需要注意的是下面的所有的操作符,在遇到null的时候,都不会抛出java.lang.NullPointerException

Operator

Method

a == b

a.equals(b) or a.compareTo(b) == 0 **

a != b

! a.equals(b)

a <=> b

a.compareTo(b)

a > b

a.compareTo(b) > 0

a >= b

a.compareTo(b) >= 0

a < b

a.compareTo(b) < 0

a <= b

a.compareTo(b) <= 0

需要注意的是,“==”操作符并不总是和equals()方法等价。

比如:
    def a = null
    def b = "foo"

    assert a != b
    assert b != a
    assert a == null

无论a或者b谁是null,都不会抛出java.lang.NullPointerException。

另外在不同类型的对象之间比较的时候,强制类型转换规则使用于把数字类型转换为最大的数字类型。所以下面的代码是有效的:

    Byte a = 12
    Double b = 10

    assert a instanceof Byte
    assert b instanceof Double

    assert a > b

猜你喜欢

转载自blog.csdn.net/a568478312/article/details/79910691