每天三分鐘瞭解Kotlin的祕密:1.基礎入門

什麼要學習Kotlin

首先,看這篇文章前,應該先明確一個問題:我們爲什麼要學習Kotlin?

如下圖所示:

而Kotlin是一門非常優秀的語言,兼容了N多種語言的優點,學習Kotlin有助於提升我們多層編程開發的認識。

從一個類開始

感謝開源項目https://github.com/githubwing/GankClient-Kotlin

以及https://github.com/huanglizhuo/kotlin-in-chinese的Kotlin翻譯

我們從GankClient的某個類開始學習Kotlin

這是Kotlin的一個樣例類(終於不用再像java一樣寫多餘的分號了):

package com.wingsofts.gankclient.mvp.model

import com.wingsofts.gankclient.api.GankApi
import com.wingsofts.gankclient.bean.FuckGoods
import com.wingsofts.gankclient.bean.JsonResult
import com.wingsofts.gankclient.mvp.contract.RandomContract
import rx.Observable
import javax.inject.Inject

class RandomModel
@Inject constructor(private val api: GankApi) : RandomContract.Model {

    override fun getRandom(type: String): Observable<JsonResult<List<FuckGoods>>> {
        return api.getRandom(type)
    }

    var counter = 0
        set(value) {
            if (value >= 0)
                field = value
        }

    fun max(a: Int, b: Int) = if (a > b) a else b
}

導包

與Java一樣,Kotlin也含有默認導入的特性。Kotlin的每個文件都默認導入瞭如下常用包,

-- kotlin.*

-- kotlin.annotation.*

-- kotlin.collections.*

-- kotlin.comparisons.* (since 1.1)

-- kotlin.io.*

-- kotlin.ranges.*

-- kotlin.sequences.*

-- kotlin.text.*

而Kotlin的導包方式和Java也類似,但有一點,Kotlin不支持靜態導入。

Kotlin爲什麼不支持靜態導入?

因爲靜態導入會增加代碼的閱讀成本。

函數聲明

fun

Kotlin 中用關鍵字 fun 聲明函數。

    override fun getRandom(type: String): Observable<JsonResult<List<FuckGoods>>> {
        return api.getRandom(type)
    }

Kotlin爲什麼使用fun來聲明函數?爲什麼不是function?或者def?

JetBrains團隊說:

We use “fun” because we like it - and yes, we do know what the word means in English.

我們使用“fun”因爲我們喜歡它,而且我們知道這個詞在英語中是啥意思!

“fun”在英語中是什麼意思?

來自谷歌翻譯的 fun 的翻譯:動詞 開玩笑,名詞 玩笑。

參數

參數聲明

Kotlin的參數使用Pascal符號定義,參數之間和java類似通過“ , ”分隔,參數需要指明類型。

    fun test(count: Int, test2: Int) {
    }

爲什麼Kotlin像Pascal一樣,參數聲明類型要在參數名後面?count: Int

Rob Pike曾解釋過這個問題:因爲這樣更加清晰易懂,當然,我覺得這樣存在很大的爭議,不過也和工程師自身的習慣有關係。

默認參數

Kotlin參數可以設置默認值,當需要忽略該參數的時候可以使用參數的默認值。Like this: off: Int = 0

    fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size ) {
    ...
    }

Kotlin參數爲什麼支持默認值?

你聽說過重載爆炸嗎?🌰

空返回值

在Java中返回空關鍵字爲void,在Kotlin中的空返回值爲Unit,並且可以省略.Unit和void不同,Unit是個真實的類並且是個單例。

// 不省略
fun printHello(name: String?): Unit {
    ...
}
// 省略
fun printHello(name: String?) {
    ...
}

爲什麼使用Unit?

“Unit” just stands for “something that has only one value”, it’s a traditional name, comes from functional languages. I agree that this name is not very intuitive, but we failed to invent a better name.

“Unit”代表“只有一個值”,它是一個來自函數式語言的傳統的名稱。我同意這個名字不是很直觀,但我們沒有想到一個更好的名字。

局部變量

Kotlin局部變量分爲val和var

var 關鍵字聲明可變屬性,和Java變量聲明類似;

val 關鍵字聲明只讀屬性,和Java中final變量類似,在初始化時需要賦值,以後不能改變。更多的應該使用val關鍵字。

    val a: Int = 1
    var x = 5

爲什麼使用val關鍵字?

val具有Immutable或readonly的特性,一旦創建,不可改變。沒有競爭條件,沒有併發問題,無需去同步,保證了線程安全,不需要擔心空安全問題。

爲什麼是val和var?

因爲val是value的縮寫,而var是variable。

Using vals in your code makes you think about alternative, immutable, functional code. […] Removing vars leads to refactoring. The refactoring leads to new coding patterns. New coding patterns leads to a shift in your approach to programming. This shift in approach leads to transformative code that has fewer defects and is easier to maintain.

— Beginning Scala, David Pollack

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