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源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。

相關文章
相關標籤/搜索