Kotlin那些不为人知的秘密:1.基础入门

949 阅读3分钟

什么要学习Kotlin

首先,看这篇文章前,应该先明确一个问题:我们为什么要学习Kotlin?

如下图所示:

k1.png

而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参数为什么支持默认值?

你听说过重载爆炸吗?🌰

2.png

空返回值

在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