Kotlin

什么是Kotlin?

Kotlin是由JetBrains设计并开源的JVM编程语言。Kotlin是使用Java开发者的思维创建的,Intellij作为它主要的开发IDE,因此对于Android开发者来说它非常易于学习并能与AS和Gradle完美结合。
它的主要特点有:
1、简洁(函数式编程减少很多代码)
2、安全(编译时就处理了各种空指针的情况)
3、轻量级(Kotlin核心库仅有不到7000个方法,大致和support-v4一样)
4、高交互性(与Java混合编程)
5、提供了更多特性

使用配置

1、Android Studio 安装插件 Kotlin(原本还有 Kotlin Extensions For Android,已合入Kotlin)
2、build.gradle 配置

buildscript {
    ext.kotlin_version = '1.0.5-2'
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlin_version}"
    }
}

apply plugin: 'kotlin-android‘
apply plugin: 'kotlin-android-extensions‘

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:${kotlin_version}"
}

基本语法

这里只列出一些与Java不同的地方,完整的语法参考文档见文章最后链接
1、基本类型
数值:Double,Float,Long,Int,Short,Byte
字符:Char
布尔:true,false

// 短类型不是长类型的子类型,需要显示转换,数值和字符都有toXXX()方法
var a: Int = 100
var b: Long = a.toLong() 

数组:Array

// 可以通过 asc[0] 或 asc.get(0) 访问元素
// 可以通过 asc.forEach{} 或 for(str in asc) {} 遍历元素
var emptyArray = emptyArray<String>() // []
var nullArray = kotlin.arrayOfNulls<String>(3) // [null, null, null]
var numArray = arrayOf(1, 2, 3) // [1, 2, 3]
var asc = Array(5, { i -> (i * i).toString() }) // ["0", "1", "4", "9", "16"]

字符串:String

var str = "hello world"
访问和遍历元素同Array

字符串模板:

var name = "Bob"
println("My name is $name") // 打印 My name is Bob

var a = 10
var b = 20
println("The sum is ${a+b}") // 打印 The sum is 30

2、变量与常量

var x: Int = 5 // 定义变量
var y = 5 // 能推导出类型,可省略类型声明
y++

val x: Int = 5 // 定义常量
val y = 5  // 能推导出类型,可省略类型声明
val z: Int  // 当没有初始化值时必须声明类型 
z=1  // 只能赋值一次

const val INT_ONE: Int = 1 // 编译时可确定值的常量可以用const修饰,但只能放在文件最外层

3、流程控制
if表达式:

var max = if (a > b) a else b 

var max = if (a > b) {
    println("choose $a")
    a
} else {
    println("choose $b")
    b
}

for表达式和Range:

for (i in 0..4) println(i) // 0,1,2,3,4
for (i in 4 downTo 0) println(i) // 4,3,2,1,0
for (i in 0..4 step 2) println(i) // 0,2,4
for (i in 4 downTo 0 step 2) println(i) // 4,2,0
for (i in 0 until 4) println(i) // 0,1,2,3

When表达式:

when(x) { 
    0 -> print("x == 0")
    1,2 -> print("x == 1 or x == 2")
    in 1..10 -> print("x is in the range") 
    is Int -> print(x + 1)
    is String -> print(x.size() + 1) // 智能转换
    else -> print("otherwise")
}

4、定义函数
fun + 函数名 + 参数 + 返回值 + 函数体

fun sum(a: Int , b: Int): Int { return a + b } 
fun sum(a: Int, b: Int) = a + b  // 与上句等价
fun printSum(a: Int, b: Int): Unit { print( a + b) } // 没有返回值时为Unit
fun printSum(a: Int, b: Int) { print( a + b) }  // Unit可省略

5、默认参数
Java:

void introduce(String name, int age) {
    println("Hi, My name is " + name + ", I am " + age);
}
void introduce(String name) {
    introduce(name, 18);
}

Kotlin:

fun introduce(name: String, age: Int = 18) {
    println("Hi, My name is $name, I am $age")
}

调用:

introduce("Bob")
introduce("Bob", 20)

6、类与构造函数
class + 类名 + 类头 + 类主体

// 最简单的类定义
class Person

// 有一个主构造函数的类,其中constructor关键字省略掉了
class Person(var id: Long, var name: String, var age: Int)

// constructor有private关键字修饰,不能省略
// 主构造函数的初始化只能在类主体的init块中
// 二级构造函数在类主体中定义,需要用this调用主构造函数
class Person private constructor(var id: Long, var name: String, var age: Int) {
    init {
        print("Person initialized with id ${id} name ${name} age ${age}") 
    }
    constructor(person: Person) : this(person.id, person.name, person.age) {
    }
}

所有的类都有共同的父类 Any
没有new关键字,直接像使用普通函数那样使用构造函数创建类实例:

var person = Person(1, "Bob", 20)

7、数据类
data class User(var id: Long, var name: String, var age: Int)
自动实现了get、set方法以及toString、equals、hashCode、copy等方法,支持映射对象到变量。

data class Forecast(var date: Date, var temp: Float, var details: String)

var f1 = Forecast(Date(), 27.5f, "Shiny day")
var f2 = f1.copy(temp = 30f) // 变量名不可随意
var (date, temp, details) = f1 // 变量名可以随意,按顺序映射

8、继承
Kotlin中所有的类和属性以及方法都默认是final的,如果需要被继承则要加上open关键字,override标记的方法默认是open的,如果不想再被继承可以加上final

open class Base {
    open fun f1(){}
    fun f2() {}
}
class Derived : Base() {
    override fun f1() {}
} 

9、接口
Kotlin中的接口可以有属性和方法的默认实现,与抽象类的区别是接口的属性是无状态的,需要子类去重写
Java:

public interface Flying {
    void fly();
}
public class Bird implements Flying {
    Wings wings = new BirdWings();
    @Override
    public void fly() {
        wings.move();
    }
}
public class Bat implements Flying {
    Wings wings = new BatWings();
    @Override
    public void fly() {
        wings.move();
    }
}

Kotlin:

interface Flying {
    var wings: Wings
    fun fly() = wings.move()
}
class Bird : Flying {
    override var wings: Wings = BirdWings()
}
class Bat : Flying {
    override var wings: Wings = BatWings()
} 

Kotlin中实现接口和继承类一样,都是通过冒号 : 继承,多个接口及类之间以逗号 , 隔开,如果方法有多个实现则必须在子类中重写方法,可以通过super<Base>指定调用哪个父类中的方法

open class A {
    open fun f () {}
}
interface B {
    fun f() {}
}
class C : A() , B{
    override fun f() {
        super<A>.f() // 调用 A.f()
        super<B>.f() // 调用 B.f() 
    }
} 

10、空安全

var user: User = null  // 这里不能通过编译. user不能是null

var user: User? = null  // user可以是 null
user.name  // 无法编译, user可能是null,需要进行判断
user?.name  // 只有在user != null时才会执行

if (user != null) {
    user.name  // 智能转换. 如果我们在之前进行了空检查,则不需要使用安全调用操作符调用 
} 

user!!.name  // 只有在确保user不是null的情况下才能这么调用,否则会抛出异常 

var name = user?.name ?: "empty"  // 使用Elvis操作符来给定一个在是null的情况下的替代值 

11、函数扩展

fun String.toast(context: Context) {
    Toast.makeText(context, this, Toast.LENGTH_SHORT).show()
}
"abc".toast(context)

var sum = fun Int.(other: Int): Int = this + other 
1.sum(2)

12、Lambda表达式

(params) -> expression
(params) -> statement
(params) -> { statements }
如果参数没用到可以省略为 () -> { statements } 甚至 { statements }

view.setOnClickListener{Log.d(TAG, "click view")}
listOf<Int>(1, 2, 3, 4, 5).filter { it > 2 }.map { it * it } // [9, 16, 25]

插件

kotlin-android-extensions插件主要提供了对Android的支持
例如:不再需要findViewById,可直接通过id引用xml中的View

textView.text = "Hello World!"; 
textView.setOnClickListener { toast(textView.text.toString()) }

anko插件引入了DSL(Domain Specific Language)的方式开发Android界面布局,主要目的是用代码代替xml实现界面布局
使用前:

<RelativeLayout>
    <TextView
        android:id="@+id/sample_text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Sample text view"
        android:textSize="25sp" />
    <Button
        android:id="@+id/sample_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/sample_text_view"
        android:text="Sample button" />
</RelativeLayout>

使用后:

relativeLayout {
    val textView = textView("Sample text view") {
        textSize = 25f
    }.lparams {
        width = matchParent
        alignParentTop()
    }
    button("Sample button").lparams {
        width = matchParent
        below(textView)
    }
}

参考文档

1、Kotlin API 中文文档
https://github.com/huanglizhuo/kotlin-in-chinese

2、Kotlin Android 开发中文文档
https://github.com/wangjiegulu/kotlin-for-Android-developers-zh

3、Kotlin:Java 6 废土中的一线希望
https://toutiao.io/posts/c55jha/preview

4、Kotlin 在线运行
http://try.kotlinlang.org/

5、Android Studio中 code->Convert Java File to Kotlin File 自动将Java文件转换成Kotlin文件

另外由于Kotlin和Java之间的高交互性,可以一边学习Kotlin的语法一边一点点的替换现有代码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容