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() 三個方法。

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。

3.字面常量值

對於整數值,有以下幾種類型的字面值常數:

  • 10進制數123
  • Long類型需要大寫L來標識,如:123L
  • 16進制數:0x0F
  • 2進制數:0b00001011

注意:
- kotlin不支持八進制。
- kotlin中浮點類型與Java相同。

4.顯示類型轉換

由於數據類型內部表達方式的差異,較小的數據類型不是較大數據類型的子類型,所以是不能進行隱式轉換的。這意味着在不進行顯式轉換的情況下,我們不能把 Int 型值賦給一個 Long 變量。也不能把 Byte 型值賦給一個 Int 變量。

如果數據之間進行轉換,則需要顯示轉換來拓寬數字。

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

打印輸出:

1000

每個數字類型都繼承Number抽象類,其中定義瞭如下的轉換函數:

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

因此,數字之間的轉換可以直接調用上面的這些函數。

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元

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章