Kotlin语法(二)

1、创建POJO

data class Customer(val name: String, val age: Int)

用data关键字创建的class相对应与java中的javabean对象类。此class默认包含以下方法:
(1)getters(如果变量为var的则会有setters),针对每个属性
(2)equals()
(3)hashCode()
(4)toString()
(5)copy()
(6)component1(), component2()….针对每个属性。这个方法不对外部显示,以后会详细解释。

2、方法参数的默认值

fun foo(a: Int = 0, b: String = ""){...}

3、List

(1)创建只读的List,只能获取list中的值,不能修改其中的值

val list = listOf("a", "b", "c")

list[0] = "d" //是不合法的

(2)创建可修改的List,每个index的值可读可写

val list = mutableListOf("a", "b", "c")
list[0] = "d" //是合法的,修改index为0的值为"d"

4、Map

(1)只读的map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

map["a"] = 4 //是可不合法的

(2)可读可写的Map

val map = mutableMapOf(Pair("a", 1), Pair("b", 2), Pair("c", 3))

map["a"] = 4 //是合法的,并且修改了key为"a"的值为4

也可以初始化java的hashmap,也为可读可写

val hashMap = hashMapOf("a" to 1, "b" to 2, "c" to 3)
hashMap["a"] = 4  //是合法的

5、扩展方法

在java中我们经常会写一些Utils类,来对一些已知类的扩展使用,在kotlin中我们可以直接为某个类写一些扩展方法,在使用时就跟使用普通方法一样。

fun String.firstChar(){
    return if(length > 0) get(0) else nul
}

fun test(){
    val c = "abc".firstChar()
    println(c)
}

打印结果为=====
a

6、判断非空的简写(not null)

val files = File("test").listFiles()
println(files?.size)  //如果files不为空时获取它的属性size,如果为空则返回null

7、操作符?:

val files = File("Test").listFiles()
println(files?.size ?: "empty") /** 如果files不为Null时返回files.size,如果files为null,则表达式files?.size为null,会返回?:后面的值empty*/

//?:操作符表示如果左边的表达式不为null则返回左边表达式的值,否则返回右边表达式的值

8、返回when表达式

when表达式可以作为一个返回值,如下代码:

fun transform(color: String): Int {
    return when(color) {
        "red"  -> 0  //// 如果符合条件则返回0
        "green"  -> 1
        "blue"  -> 2
        else    -> throw IllegalArgumentException("Invalid color param value")
    }
}

9、try/cache表达式

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }
    // Working with result
}

10、if表达式

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

11、单一表达式

fun theAnswer() = 42

12、调用一个对象实例的多个方法(with)

class Turtle {
    fun penDown()
    fun penUp()
    fun turn(degrees: Double)
    fun forward(pixels: Double)
}

fun callI(){
    val myTurtle = Turtle()
    with(myTurtle) { // 以下默认调用的都是myTurtle的方法
        penDown()
        for(i in 1..4){
            forWard(100.0)
            turn(90.0)
        }
        penUp()
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章