Kotlin中的基本类型(—)

1.Any根类型

Kotlin 中全部类都有一个共同的超类 Any ,若是类声明时没有指定超类,则默认为 Any。Any在运行时,其类型自动映射成java.lang.Object。在Java中Object类是全部引用类型的父类。可是不包括基本类型:byte int long等,基本类型对应的包装类是引用类型,其父类是Object。而在Kotlin中,直接统一,全部类型都是引用类型,统一继承父类Any。Any是Java的等价Object类。可是跟Java不一样的是,Kotlin中语言内部的类型和用户定义类型之间,并无像Java那样划清界限。它们是同一类型层次结构的一部分。Any 只有 equals() 、 hashCode() 和 toString() 三个方法。 java

Any源码:
public open class Any {
    /**
     * Indicates whether some other object is "equal to" this one. Implementations must fulfil the following
     * requirements:
     *
     * * Reflexive: for any non-null reference value x, x.equals(x) should return true.
     * * Symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
     * * Transitive:  for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
     * * Consistent:  for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
     *
     * Note that the `==` operator in Kotlin code is translated into a call to [equals] when objects on both sides of the
     * operator are not null.
     */
    public open operator fun equals(other: Any?): Boolean

    /**
     * Returns a hash code value for the object.  The general contract of hashCode is:
     *
     * * Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
     * * If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.
     */
    public open fun hashCode(): Int

    /**
     * Returns a string representation of the object.
     */
    public open fun toString(): String
}

2.数字类型

类型 宽度(Bit)
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

注意:在 Kotlin 中字符Char不是数字。这些基本数据类型,会在运行时自动优化为Java的double、float、long、int、short、byte。web

3.字面常量值

对于整数值,有如下几种类型的字面值常数: app

  • 10进制数123
  • Long类型须要大写L来标识,如:123L
  • 16进制数:0x0F
  • 2进制数:0b00001011

注意:
- kotlin不支持八进制。
- kotlin中浮点类型与Java相同。ide

4.显示类型转换

因为数据类型内部表达方式的差别,较小的数据类型不是较大数据类型的子类型,因此是不能进行隐式转换的。这意味着在不进行显式转换的状况下,咱们不能把 Int 型值赋给一个 Long 变量。也不能把 Byte 型值赋给一个 Int 变量。 svg

若是数据之间进行转换,则须要显示转换来拓宽数字。 函数

val mTest: Long = 1000
val mInt: Int = mTest.toInt() // 显式拓宽
println(mInt)

打印输出:大数据

1000flex

每一个数字类型都继承Number抽象类,其中定义了以下的转换函数:优化

toDouble(): Double 
toFloat(): Float 
toLong(): Long 
toInt(): Int 
toChar(): Char 
toShort(): Short 
toByte(): Byte 

所以,数字之间的转换能够直接调用上面的这些函数。ui

5.运算符

Kotlin支持数字运算的标准集,运算被定义为相应的类成员(但编译器会将函数调用优化为相应的指令)。如下是位运算符的完整列表(适用于Int和Long类型):

  • shl(bits) – 带符号左移 (等于 Java 的<<)
  • shr(bits) – 带符号右移 (等于 Java 的 >>)
  • ushr(bits) – 无符号右移 (等于 Java 的 >>>)
  • and(bits) – 位与(and)
  • or(bits) – 位或(or)
  • xor(bits) – 位异或(xor)
  • inv() – 位非

6.Char字符(Character)类型与转义符(Escape character)

在kotlin中,Char表示字符,不能直接看成数字。字符字面值用 单引号 括起来。

7.Boolean布尔类型

Kotlin的布尔类型用 Boolean 类来表示,与Java同样,它有两个值:true 和 false。

Boolean源码:
public class Boolean private constructor() : Comparable<Boolean> {
    /** * Returns the inverse of this boolean. */
    public operator fun not(): Boolean

    /**
     * Performs a logical `and` operation between this Boolean and the [other] one. Unlike the `&&` operator,
     * this function does not perform short-circuit evaluation. Both `this` and [other] will always be evaluated.
     */
    public infix fun and(other: Boolean): Boolean

    /**
     * Performs a logical `or` operation between this Boolean and the [other] one. Unlike the `||` operator,
     * this function does not perform short-circuit evaluation. Both `this` and [other] will always be evaluated.
     */
    public infix fun or(other: Boolean): Boolean

    /**
     * Performs a logical `xor` operation between this Boolean and the [other] one.
     */
    public infix fun xor(other: Boolean): Boolean

    public override fun compareTo(other: Boolean): Int
}

从Boolean源码中能够看出,内置的运算发有:
- ! 逻辑非 not()
- && 短路逻辑与 and()
- || 短路逻辑或or()
- xor 异或(相同false,不一样true)

Boolean还继承实现了Comparable的compareTo()函数。

compareTo():
println(false.compareTo(true))
println(true.compareTo(true))

打印输出:

-1
0

8.String字符串类型

Kotlin的字符串用 String类型表示。对应Java中的java.lang.String。字符串是不可变的。String一样是final不可继承的。

String源码:
public class String : Comparable<String>, CharSequence {
    companion object {}

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

    public override val length: Int

    public override fun get(index: Int): Char

    public override fun subSequence(startIndex: Int, endIndex: Int): CharSequence

    public override fun compareTo(other: String): Int
}
重载+操做符

kotlin中String字符串的重载操做符做用对象能够是任何对象,包括空引用。

val mName: String = "秦川小将"
println(mName.plus(100))
println(mName.plus("qinchuanxiaojiang"))
println(mName.plus(true))

打印输出:

秦川小将100
秦川小将qinchuanxiaojiang
秦川小将true

获取length
val mName: String = "秦川小将"
println(mName.length)

打印输出:

4

索引运算符

kotlin中String字符串提供了一个get(index: Int)函数方法,使用该方法能够将每个元素经过索引来一一访问。

val mName: String = "秦川小将"
println(mName[0]) println(mName[1]) println(mName[2]) println(mName[3])

打印输出:




for循环迭代字符串

也能够经过for循环来迭代字符串

val mName: String = "秦川小将"
for (name in mName){
    println(name)
}

打印输出:




截取字符串
val mName: String = "秦川小将"
println(mName.subSequence(0, 1))
println(mName.subSequence(mName.length - 2, mName.length))

打印输出:


小将

9.字符串字面值

字符串的字面值,能够包含原生字符串能够包含换行和任意文本,也能够是带有转义字符的转义字符串。

val mName1: String = "秦\t\t\t将"
println(mName1)

打印输出:

秦 川 小 将

转义采用传统的反斜杠方式,原生字符串使用三个引号(”“”)分界符括起来,内部没有转义而且能够包含换行和任何其余字符:

val mText: String = """ for (text in "kotlin"){ print(text) } """
println(mText)

打印输出:

for (text in "kotlin"){  
    print(text)  
}

在package kotlin.text下面的Indent.kt代码中,Kotlin还定义了String类的扩展函数:

public fun String.trimMargin(marginPrefix: String = "|"): String = replaceIndentByMargin("", marginPrefix)
public fun String.trimIndent(): String = replaceIndent("")

能够使用trimMargin()、trimIndent()裁剪函数来去除前导空格。能够看出,trimMargin()函数默认使用 “|” 来做为边界字符:

val mText: String = """Hello! |你们好 |我是秦川小将 """.trimMargin()
println(mText)

打印输出:

Hello!
你们好
我是秦川小将

默认 | 用做边界前缀,但能够选择其余字符并做为参数传入,好比 trimMargin(“>”)。trimIndent()函数,则是把字符串行的左边空白对齐切割:

val mText1: String = """Hello! |你们好 |我是秦川小将 """.trimMargin(">")
println(mText1)

打印输出:

Hello!  
    你们好  
    我是秦川小将

10.字符串模板

字符串能够包含模板表达式,即一些小段代码,会求值并把结果合并到字符串中。 模板表达式以美圆符( ) 开 头 , 或 者 用 花 括 号 扩 起 来 的 任 意 表 达 式 {},原生字符串和转义字符串内部都支持模板,这几种都由一个简单的名字构成:

val mPrice: Double = 100.0
val mPriceStr: String = "单价:$mPrice"
val mDetail: String = "这个东西${mPrice}元"
println(mPriceStr)
println(mDetail)

打印输出:

单价:100.0
这个东西100.0元

本文分享 CSDN - 秦川小将。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索