kotlin的学习笔记。

基础

函数 变量

  1. main函数可以独立于class

  2. 静态函数
    类的静态函数,需要通过将函数放入到companion object的大括号内。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class Static {
    companion object {
    fun add( a: Int, b:Int):Int = (
    a + b
    )
    }

    }

    fun main(args: Array<String>) {
    Static.add(1,2);

    }
  3. 字符串模板

    1
    2
    3
    fun main(args: Array<String>) {
    println("Hello, ${if (args.size > 0) args[0] else "someone"}!")
    }
  4. 常量用val,变量用var

    类和属性

  5. 自定义的获取器

    1
    2
    3
    4
    5
    6
    class Rectangle(val height: Int, val width: Int) {
    val isSquare: Boolean
    get() { // 属性的获取函数声明
    return height == width
    }
    }
  6. Kotlin源代码布局

    1. Kotlin并没有在导入类和函数之间做区别,可以直接import方法,类似python和ReactJs的用法。
    2. 可以把多个类放到同一个文件中并且可以为文件选择任意的名字,弱化了包的概念

枚举

枚举和java中的有很大的相似之处,可以自己定义参数。

1
2
3
4
5
6
7
8
enum class Color(val r :Int, val g :Int, val b :Int) {// 1 声明枚举常量的属性
RED(255, 0, 9), ORANGE(255, 255, 0), // 2 当每个常量被创建时指定属性值

YELLOW(255, 255, 0), GREEN(0, 255, 0), BLUE(0, 0, 255),

INDIGO(75, 0, 130), VIOLET(238, 130, 238); // 3 分号(;)在这里是必须的

fun rgb() = (r * 256 + g) * 256 + b // 4 在枚举类中定义了一个方法

不同之处在于:

  1. enum class 来标识是枚举
  2. 在枚举中的常量,需要用分号隔开,kotlin中唯一一处需要必须用分开的地方

    when

    when在处理枚举时,有点类似于java的switch-case,不过在kotlin中可以直接使用表达式函数。

带参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 fun getMnmonic(color: Color) =        // 1 直接返回一个when表达式
when (color) { // 2 如果颜色等于枚举常量,返回对应的字符串
Color.RED -> "Richard"
Color.ORANGE -> "Of"
Color.YELLOW -> "York"
Color.GREEN -> "Grave"
Color.BLUE -> "Battle"
Color.INDIGO -> "In"
Color.VIOLET -> "Vain"

else -> throw Exception("Dirty color") // 3 如果没有一个分支被匹配,将执行该语句
}

`

对应多个条件满足同一个返回结果,可以:

1
Color.RED, Color.ORANGE, Color.YELLOW -> "warm"

还有一个分支是默认分支,可以通过else的方式返回。

不带参数

对于多个参数的,每次都要写参数,会很多余,可以直接不用参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
when {    // 不带参数的when
(c1 == RED && c2 == YELLOW) ||
(c1 == YELLOW && c2 == RED) ->
ORANGE

(c1 == YELLOW && c2 == BLUE) ||
(c1 == BLUE && c2 == YELLOW) ->
GREEN

(c1 == BLUE && c2 == VIOLET) ||
(c1 == VIOLET && c2 == BLUE) ->
INDIGO

else -> throw Exception("Dirty color")
}

智能类型转换

在java中,在调用一个是其他类型的对象时,若是object对象,我们需要先转成对应的类型,而后再处理,但是在kotlin不需要,只要判断是某个类型后,可以直接调用这个类具有的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Expr
class Num(val value: Int) : Expr // 1 带有一个属性、值而且实现了Expr接口的简单的值对象类
class Sum(val left: Expr, val right: Expr) : Expr // 2 求和操作的参数可以是任意的Expr:Num对象或者其他的Sum对象


fun eval(e: Expr): Int {
if (e is Num) {
val n = e as Num // 1 显式的Num类型转换是多余的
return e.value
}
if (e is Sum) {
return eval(e.right) + eval(e.left) // 2 变量e是智能类型转换
}
throw IllegalArgumentException("Unknown expression")
}

fun main(args: Array<String>) {
println(eval(Sum(Sum(Num(1), Num(2)), Num(4))))
}