Kotlin

Kotlin基础(8)-操作符重载

2019-11-08  本文已影响0人  取了个很好听的名字

前言

本文主要简单介绍一下kotlin的操作符重载。

什么是操作符重载

在Java中你有没有注意到这样一个现象

        int a=1;
        int b=2;
        int c=a+b;//3
        String a="aaa"
        String b="bbb"
        String c=a+b//"aaabbb"

明明使用的是同样的操作符操作,为什么一个是实现数值上的相加,一个是实现字串的连接,原因就是操作符的重载

操作符重载:所谓的操作符重载,就是通过编程的方式赋予操作符不同的含义。这也就是Int和String对“+”这个操作符赋予了不同的含义。那么我们自己的类想要实现操作符重载要怎么办呢?答案就是重载一系列的方法。

kotlin提供了可以重载的操作符,除了这些操作符,其他的操作符均不可以进行重载,Kotlin中允许的重载操作符如下:

一元操作符

操作符 对应方法
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()

示例代码如下:
MyClass.kt


    //+A
     operator  fun unaryPlus():A{
         if(this.x>0){
             return A(x)
         }else{
             return A(-x)
         }
     }

    //-A
    operator  fun  unaryMinus():A{
        return A(-x)
    }

    //!A
    operator  fun not():String{
           return  "执行了not中的代码"
    }

       var a = A(-10)
        //一元前缀操作符
        Log.e("a", "${a.x}")
        Log.e("+a", "${+a.x}")
        Log.e("-a", "${-a.x}")
        Log.e("!a", "${!a}")

测试结果

11-08 11:01:26.632 9412-9412/? E/a: -10
11-08 11:01:26.632 9412-9412/? E/+a: -10
11-08 11:01:26.632 9412-9412/? E/-a: 10
11-08 11:01:26.632 9412-9412/? E/!a: 执行了not中的代码

自增自减操作符

操作符 对应方法
a++/++a a.inc()
a--/--a a.dec()

示例代码

 //A++
    operator  fun  inc():A{
        return A(this.x+1)
    }

    //A--
    operator  fun dec():A{
        return A(this.x-1)
    }

       var b = A(10)
        //自增自减操作符
        Log.e("b++", "${b++.x}")
        Log.e("b", "${b.x}")

        Log.e("b--", "${b--.x}")
        Log.e("b", "${b.x}")

测试结果

11-08 11:29:27.753 11191-11191/com.zhqy.javademo E/b++: 10
11-08 11:29:27.753 11191-11191/com.zhqy.javademo E/b: 11
11-08 11:29:27.753 11191-11191/com.zhqy.javademo E/b--: 11
11-08 11:29:27.753 11191-11191/com.zhqy.javademo E/b: 10

算数运算符

操作符 对应方法
a+b a.plus(b)
a-b a.minus(b)
a*b a.times(b)
a/b a.div(b)

示例代码

  //a+b
    operator  fun plus(oper :A):A{
        var result=this.x+oper.x
        return A(result)
    }
    //a-b
    operator  fun  minus(oper: A):A{
        var result=this.x-oper.x;
        return A(result)
    }

    //a*b
    operator  fun times(oper:A):A{
        val result=this.x*oper.x
        return A(result)
    }

    //a/b
    operator  fun div(oper:A):A{
        var result=this.x/oper.x
        return A(result)
    }

        var c = A(2)
        var d = A(3)

        Log.e("c+d", "${(c + d).x}")
        Log.e("c-d", "${(c - d).x}")
        Log.e("c*d", "${(c * d).x}")
        Log.e("c/d", "${(c / d).x}")
        Log.e("c..d", "${c..d}")

测试结果

11-08 11:29:27.755 11191-11191/com.zhqy.javademo E/c+d: 5
11-08 11:29:27.755 11191-11191/com.zhqy.javademo E/c-d: -1
11-08 11:29:27.755 11191-11191/com.zhqy.javademo E/c*d: 6
11-08 11:29:27.755 11191-11191/com.zhqy.javademo E/c/d: 0
11-08 11:29:27.756 11191-11191/com.zhqy.javademo E/c..d: 2..3

in运算符

操作码 对应方法
a in b b.contains(a)
a !in b !b.contains(a)

示例代码

class Position(var list:List<Int>){
    //in
    operator  fun contains(value:Int):Boolean{
        return value in  list
    }

}

        //in操作符
        var list = mutableListOf<Int>(1, 2, 3)
        var position = Position(list)
        var value: Int = 1
        Log.e("value in position", "${value in position}")

测试结果

11-08 11:29:27.760 11191-11191/com.zhqy.javademo E/value in position: true

索引访问运算符

操作码 对应方法
a[i] a.get(i)
a[i,j] a.get(i,j)
a[i_1,...,...,i_n] a.get(i_1...i_n)
a[i]=b a.set(i,b)
a[i,j]=b a.set(i,j,b)
a[i_1,....,i_n]=b a.set(i_1,....,i_n,b)

示例代码

 //a[x]
    operator  fun get(position:Int):Int{
        if (position<list.size){
            return list.get(position)
        }else{
              throw  RuntimeException("错啦")
        }

    }

    //a[x]=x
    operator  fun set(position:Int,value:Int){
        var i = list[position]
        val mapIndexedNotNull = list.mapIndexedNotNull { index, i -> if (index == position) value else i }
        this.list=mapIndexedNotNull
    }

        //索引访问

        Log.e("position[0]", "${position[0]}")
        position[0] = 100;
        Log.e("position[0]", "${position[0]}")

测试结果

11-08 11:29:27.760 11191-11191/com.zhqy.javademo E/position[0]: 1
11-08 11:29:27.760 11191-11191/com.zhqy.javademo E/position[0]: 100

调用操作符

操作符 对应方法
a() a.invoke()
a(i) a.invoke(i)
a(i,j) a.invoke(i,j)
a(i,...,j) a,invoke(i,...,j)

示例代码

 //invoke
    operator  fun invoke():String{
        return "invokez执行了"

    }

    //invoke
        Log.e("invoke", "${a()}")

测试结果如下

11-08 11:29:27.760 11191-11191/com.zhqy.javademo E/invoke: invokez执行了

广义操作符

操作符 对应方法
a+=b a.plusAssign(b)
a-=b a.minusAssign(b)
a*=b a.timesAssign(b)
a/=b a.divAssign(b)
a%=b a.remAssign(b)

示例代码

  //a-=b
    operator  fun minusAssign(oper:Int){
        this.x-=oper
    }


    //a*=b
    operator  fun timesAssign(oper :Int){
        this.x*=oper
    }

    //a/=b
    operator  fun divAssign(oper: Int){
        this.x/=oper
    }
    // a%=b
    operator  fun remAssign(oper:Int){
        this.x%=oper
    }

        //广义操作符
        c += d.x
        Log.e("c+=d", "${c.x}")
        c -= d.x
        Log.e("c-=d", "${c.x}")
        c *= d.x
        Log.e("c*=d", "${c.x}")
        c /= d.x
        Log.e("c/=d", "${c.x}")
        c%=d.x
        Log.e("c%=d","${c.x}")

测试结果

11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c+=d: 5
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c-=d: 2
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c*=d: 6
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c/=d: 2
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c%=d: 2

相等/不相等操作符

操作符 对应方法
a==b a?.equals(b)?:(b===null)
a!=b !(a?.equals(b)?:(b===null))

示例代码

 //相等不相等
    override fun equals(other: Any?): Boolean {
       if (other is A){
           return other?.x==this.x
       }
        return  false

    }

  //相等与不相等操作符

        Log.e("c==d", "${c == d}")
        Log.e("c!=d", "${c != d}")

测试结果

11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c==d: false
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c!=d: true

需要注意的是equals是重写父类的equals的方法,用override进行修饰

比较操作符

操作符 对应方法
a>b a.compareTo(b)>0
a>=b a.compareTo(b)>=0
a<b a.compareTo(b)<0
a<=b a.compareTo(b)<=0

测试代码

   //比较操作符
    operator  fun compareTo(oper:A):Int{
        return this.x-oper.x
    }

        //比较操作符
        Log.e("c>d", "${c > d}")
        Log.e("c>=d", "${c >= d}")
        Log.e("c<d", "${c < d}")
        Log.e("c<=d", "${c <= d}")

测试结果

11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c>d: false
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c>=d: false
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c<d: true
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c<=d: true

全部示例代码如下

package com.zhqy.javademo

import android.content.ComponentName
import android.util.Log
import java.lang.RuntimeException

/**
 * Created by jackal on 2019/11/1.
 */
class A(var x:Int){

    //+A
     operator  fun unaryPlus():A{
         if(this.x>0){
             return A(x)
         }else{
             return A(-x)
         }
     }

    //-A
    operator  fun  unaryMinus():A{
        return A(-x)
    }

    //!A
    operator  fun not():String{
           return  "执行了not中的代码"
    }

    //A++
    operator  fun  inc():A{
        return A(this.x+1)
    }

    //A--
    operator  fun dec():A{
        return A(this.x-1)
    }

    //a+b
    operator  fun plus(oper :A):A{
        var result=this.x+oper.x
        return A(result)
    }
    //a-b
    operator  fun  minus(oper: A):A{
        var result=this.x-oper.x;
        return A(result)
    }

    //a*b
    operator  fun times(oper:A):A{
        val result=this.x*oper.x
        return A(result)
    }

    //a/b
    operator  fun div(oper:A):A{
        var result=this.x/oper.x
        return A(result)
    }

    // a..b
    operator  fun rangeTo(oper :A):IntRange{
        return this.x..oper.x
    }

    //invoke
    operator  fun invoke():String{
        return "invokez执行了"

    }

    //a+=b
    operator  fun plusAssign(oper :Int){

        this.x=this.x+oper

    }


    //a-=b
    operator  fun minusAssign(oper:Int){
        this.x-=oper
    }


    //a*=b
    operator  fun timesAssign(oper :Int){
        this.x*=oper
    }

    //a/=b
    operator  fun divAssign(oper: Int){
        this.x/=oper
    }
    // a%=b
    operator  fun remAssign(oper:Int){
        this.x%=oper
    }

    //相等不相等
    override fun equals(other: Any?): Boolean {
       if (other is A){
           return other?.x==this.x
       }
        return  false

    }

    //比较操作符
    operator  fun compareTo(oper:A):Int{
        return this.x-oper.x
    }


}


class Position(var list:List<Int>){
    //in
    operator  fun contains(value:Int):Boolean{
        return value in  list
    }

    //a[x]
    operator  fun get(position:Int):Int{
        if (position<list.size){
            return list.get(position)
        }else{
              throw  RuntimeException("错啦")
        }

    }

    //a[x]=x
    operator  fun set(position:Int,value:Int){
        var i = list[position]
        val mapIndexedNotNull = list.mapIndexedNotNull { index, i -> if (index == position) value else i }
        this.list=mapIndexedNotNull
    }


}

MainActivity.kt

package com.zhqy.javademo

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import kotlin.math.log

class MainActivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var a = A(-10)
        //一元前缀操作符
        Log.e("a", "${a.x}")
        Log.e("+a", "${+a.x}")
        Log.e("-a", "${-a.x}")
        Log.e("!a", "${!a}")
        var b = A(10)
        //自增自减操作符
        Log.e("b++", "${b++.x}")
        Log.e("b", "${b.x}")

        Log.e("b--", "${b--.x}")
        Log.e("b", "${b.x}")

        //算数运算符
        var c = A(2)
        var d = A(3)

        Log.e("c+d", "${(c + d).x}")
        Log.e("c-d", "${(c - d).x}")
        Log.e("c*d", "${(c * d).x}")
        Log.e("c/d", "${(c / d).x}")
        Log.e("c..d", "${c..d}")


        //in操作符
        var list = mutableListOf<Int>(1, 2, 3)
        var position = Position(list)
        var value: Int = 1
        Log.e("value in position", "${value in position}")


        //索引访问

        Log.e("position[0]", "${position[0]}")
        position[0] = 100;
        Log.e("position[0]", "${position[0]}")

        //invoke
        Log.e("invoke", "${a()}")


        //广义操作符
        c += d.x
        Log.e("c+=d", "${c.x}")
        c -= d.x
        Log.e("c-=d", "${c.x}")
        c *= d.x
        Log.e("c*=d", "${c.x}")
        c /= d.x
        Log.e("c/=d", "${c.x}")
        c%=d.x
        Log.e("c%=d","${c.x}")


        //相等与不相等操作符

        Log.e("c==d", "${c == d}")
        Log.e("c!=d", "${c != d}")


        //比较操作符
        Log.e("c>d", "${c > d}")
        Log.e("c>=d", "${c >= d}")
        Log.e("c<d", "${c < d}")
        Log.e("c<=d", "${c <= d}")


    }
}

全部测试结果

11-08 11:53:02.260 12279-12279/com.zhqy.javademo E/a: -10
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/+a: -10
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/-a: 10
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/!a: 执行了not中的代码
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/b++: 10
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/b: 11
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/b--: 11
11-08 11:53:02.261 12279-12279/com.zhqy.javademo E/b: 10
11-08 11:53:02.262 12279-12279/com.zhqy.javademo E/c+d: 5
11-08 11:53:02.263 12279-12279/com.zhqy.javademo E/c-d: -1
11-08 11:53:02.263 12279-12279/com.zhqy.javademo E/c*d: 6
11-08 11:53:02.263 12279-12279/com.zhqy.javademo E/c/d: 0
11-08 11:53:02.264 12279-12279/com.zhqy.javademo E/c..d: 2..3
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/value in position: true
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/position[0]: 1
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/position[0]: 100
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/invoke: invokez执行了
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c+=d: 5
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c-=d: 2
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c*=d: 6
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c/=d: 2
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c%=d: 2
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c==d: false
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c!=d: true
11-08 11:53:02.268 12279-12279/com.zhqy.javademo E/c>d: false
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c>=d: false
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c<d: true
11-08 11:53:02.269 12279-12279/com.zhqy.javademo E/c<=d: true

以上就是本文的全部内容。

上一篇 下一篇

猜你喜欢

热点阅读