Kotlin:基本类型及操作符重载

简介

本文主要介绍Kotlin中用到的基本数据类型,以及操作符重载相关的知识。之所以把这两个合起来讲,主要是因为在Kotlin的基本类型中,都用到了操作符重载的相关知识

基本类型

在Kotlin中,所有的东西都是对象,因此Kotlin中描述的基本类型也不例外,只不过看起来很普通而已

  • 数字

Kotlint提供的表示数字的类型有Byte、Short、Int、Long、Float、Double,注意这里首字母都是大写,可以用如下对应表表示:

类型位数表示实例
Double6412.5/12.5e10
Float3212.5f/12.5F
Long6412L
Int3212
Short1612
Byte812

对于每一个基本类型,都有MIN_VALUE和MAX_VALUE来表示最小值和最大值,比如Byte:

   companion object {
        /**
         * A constant holding the minimum value an instance of Byte can have.
         */
        public const val MIN_VALUE: Byte = -128
        /**
         * A constant holding the maximum value an instance of Byte can have.
         */
        public const val MAX_VALUE: Byt e = 127
    }

除了上述表中的表示方法,还可以用下划线表示(1.1开始),如:

var oneMillion : Int= 1_000_000

Kotlin中,这些基本类型之间是不能进行隐式转换的,这一点和java是不同的,例如:

var byte : Byte = 2
var int : Int = byte//这种写法是错误的,较小类型不能直接转换为较大类型

虽然不能直接转换,但是可以用to***的形式进行。因为Kotlin的这些表示数字的类型,都是继承自Number的:

public abstract class Number {
    public abstract fun toDouble(): Double

    public abstract fun toFloat(): Float

    public abstract fun toLong(): Long

    public abstract fun toInt(): Int

    public abstract fun toChar(): Char

    public abstract fun toShort(): Short

    public abstract fun toByte(): Byte
}

因此想转换成什么类型,不管是向上还是向下,直接to***就行。这个是赋值的转换方式,还有一种是四则运算过程中的转换,在下面的操作符重载中会进行讲解
字符用Char表示,其不能直接当成数字。给字符赋值时,用单引号括起来,对于特殊字符有转义字符:
\t   \b  \n  \’   \”  \  $

  • 布尔

布尔用Boolean表示,只有两个值:true、false
布尔的运算有三种:
||(短路或)  &&(短路与)  !(非)

  • 字符串

字符串用String表示,可以用索引运算符访问s[i]以及for循环访问

for(c in s) {

}

以上就简单的说明了几个常用的类型,数组此处没有说,下面要说下操作符重载,这个还是比较有意思的

操作符重载

以前在学习c++的时候是有操作符重载的,后来学习Java就再也没遇到这个东西,在看Kotlin的时候出现了这个玩意。所谓的操作符重载,就是为自己的类型提供预定义的一组操作符的实现,这么说有点不好理解。举个简单的例子,在Kotlin中所有的东西都看成是对象,那么上面介绍的基本类型,比如Int也是对象,既然是对象,那么对象之间进行的一些操作肯定要通过fun定义的函数来表示,但是在Int进行四则运算中,我们直接用+、-等符号直接连接也能成功,这就是操作符重载。即:用一个符号表示一个函数,在书写的时候,需要用operator修饰符进行标记。下面先列下这些操作符的约定,然后再进行说明:

  • 一元操作
表达式函数式
+aa.unaryPlus()
-aa.unaryMinus
!aa.not()
a++a.inc()
a- -a.dec()
  • 二元操作
表达式函数式
a+ba.plus(b)
a-ba.minus(b)
a*ba.times(b)
a/ba.div(b)
a%ba.rem(b)
a..ba.rangeTo(b)
a in bb.contains(a)
a!inb!b.contains(a)
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]=ba.set(i,b)
a[i][j]=ba.set(i,j,b)
a[i_1,…,i_n]=ba.set(i_1,…,i_n,b)
a()a.invoke()
a(i)a.invoke(i)
a(i,j)a.invoke(i,j)
a(i_1,…,i_n)a.invoke(i_1,…,i_n)
a+=ba.plusAssign(b)
a-=ba.minusAssign(b)
a*=bba.timesAssign(b)
a/=ba.divAssign(b)
a%=ba.modAssign(b)
a==ba?.equals(b)?:(b==null)
a!=b!(a?.equals(b)?:(b==null)
a>ba.compareTo(b) > 0
a< ba.compareTo(b) < 0
a>=ba.compareTo(b) >= 0
a<=ba.compareTo(b) <= 0

操作符先列到这,看到左边的表达式,最先想到的是加减乘除等等,如果可以,还是不要这么认为,因为这些表达式在Int等表示数字的类型里面是加减乘除等等,但是在其他类型里面,其只代表一个符号,具体代表什么含义,需要在后面的函数式里面实现才可以知道。先从Int等表示数字的说起(只举例Int)

/** Adds the other value to this value. */
    public operator fun plus(other: Byte): Int
    /** Adds the other value to this value. */
    public operator fun plus(other: Short): Int
    /** Adds the other value to this value. */
    public operator fun plus(other: Int): Int
    /** Adds the other value to this value. */
    public operator fun plus(other: Long): Long
    /** Adds the other value to this value. */
    public operator fun plus(other: Float): Float
    /** Adds the other value to this value. */
    public operator fun plus(other: Double): Double

    /** Subtracts the other value from this value. */
    public operator fun minus(other: Byte): Int
    /** Subtracts the other value from this value. */
    public operator fun minus(other: Short): Int
    /** Subtracts the other value from this value. */
    public operator fun minus(other: Int): Int
    /** Subtracts the other value from this value. */
    public operator fun minus(other: Long): Long
    /** Subtracts the other value from this value. */
    public operator fun minus(other: Float): Float
    /** Subtracts the other value from this value. */
    public operator fun minus(other: Double): Double

    /** Multiplies this value by the other value. */
    public operator fun times(other: Byte): Int
    /** Multiplies this value by the other value. */
    public operator fun times(other: Short): Int
    /** Multiplies this value by the other value. */
    public operator fun times(other: Int): Int
    /** Multiplies this value by the other value. */
    public operator fun times(other: Long): Long
    /** Multiplies this value by the other value. */
    public operator fun times(other: Float): Float
    /** Multiplies this value by the other value. */
    public operator fun times(other: Double): Double

    /** Divides this value by the other value. */
    public operator fun div(other: Byte): Int
    /** Divides this value by the other value. */
    public operator fun div(other: Short): Int
    /** Divides this value by the other value. */
    public operator fun div(other: Int): Int
    /** Divides this value by the other value. */
    public operator fun div(other: Long): Long
    /** Divides this value by the other value. */
    public operator fun div(other: Float): Float
    /** Divides this value by the other value. */
    public operator fun div(other: Double): Double

    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Byte): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Short): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Int): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Long): Long
    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Float): Float
    /** Calculates the remainder of dividing this value by the other value. */
    @Deprecated("Use rem(other) instead", ReplaceWith("rem(other)"), DeprecationLevel.WARNING)
    public operator fun mod(other: Double): Double

    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Byte): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Short): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Int): Int
    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Long): Long
    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Float): Float
    /** Calculates the remainder of dividing this value by the other value. */
    @SinceKotlin("1.1")
    public operator fun rem(other: Double): Double

    /** Increments this value. */
    public operator fun inc(): Int
    /** Decrements this value. */
    public operator fun dec(): Int
    /** Returns this value. */
    public operator fun unaryPlus(): Int
    /** Returns the negative of this value. */
    public operator fun unaryMinus(): Int

     /** Creates a range from this value to the specified [other] value. */
    public operator fun rangeTo(other: Byte): IntRange
     /** Creates a range from this value to the specified [other] value. */
    public operator fun rangeTo(other: Short): IntRange
     /** Creates a range from this value to the specified [other] value. */
    public operator fun rangeTo(other: Int): IntRange
     /** Creates a range from this value to the specified [other] value. */
    public operator fun rangeTo(other: Long): LongRange

好多啊,头都大了,但是拿这个和上面的表对以下,是不是可以知道为什么Int等表示数字的类型可以用很多类似+ -等的符号,因为Int实现的plus对于Int表示两个数相加,因此+符号在Int中表示的含义是加,就这么简单。同时再看一个例子:String

public operator fun plus(other: Any?): String

String实现了plus,因此对String也可以用+符号来进行拼接,就是这么个道理。如果还不懂,那么我们可以自己进行实现,就拿+符号来表示,记住,这里只代表一个符号,在不同的场景代表的含义不同,如下:

class Person(name : String, age : Int){
    var name : String = "no name"
    var age : Int = 0
    init {
        this.name = name
        this.age = age
    }
    public operator fun plus(person : Person) {
        println("Person: ${this.name} and Person: ${person.name}  sum age is :${this.age + person.age}")
    }
}

//然后执行如下操作:
var person1 = Person("p1", 10)
var person2 = Person("p2",20)
person1 + person2
//得到的结果:
Person: p1 and Person: p2  sum age is :30

其他操作符也是同理

小结

上面只是对基本类型和操作符重载做了一些简单的介绍,操作符重载在自定义使用的过程中还是要慎重的,毕竟很多操作符在我们的脑海里已经形成了固定的思维方式,如果定义成其他含义,可能是很难理解的,但是在理解的过程中,可以把那些符号仅仅当成一种符号,不要过多的去赋予太多含义,针对具体的场景看对应的实现即可,

最后有不对的地方欢迎指正, 谢谢

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值