Kotlin初阶(1)

·  阅读 536

这里是另外一篇,入口:Kotlin初阶(2)

Kotlin初阶易错知识点

1、不需要分号,不需要分号,不需要分号

2、字段定义://var 可变变量;val 常量

例如:

var a: Int = 1
val b = 2
val c: Int = 0
var d: Int = 0
复制代码

3、字符串的定义,去掉空格

    var age: String? = "abc" //加 ? 可为空
    val age2 = age!!.toInt() //抛出空指针异常
    val age3 = age?.toInt() //不做处理,返回null
    val age4 = age?.toInt() ?: -1 //age为空时,返回-1

text.trimMargin()
复制代码

4、list,数组是不型变的(invariant)

val items = listOf("item1", "item2", "item3")
        for (item in items) {
            println(item)
        }
        for (index in items.indices) {
            println("item at $index is ${items[index]}")
        }
        //输出
//        item at 0 is apple
//        item at 1 is banana
//        item at 2 is kiwi
复制代码

5、数组

        //[1,2,3]
        val a = arrayOf(1, 2, 3)

        //[0,2,4]
        val b = Array(3, { i -> (i * 2) })

        for (i in a.indices) {
            println("eche element : " + a[i])
        }
复制代码

6、运算符(>/</=/>=/<=/!=)

if-else
复制代码

7、运算逻辑when(X)可以传int,enum等

    val sss = 5
    val validNumbers = 11..19
        when (sss) {
            0, 1 -> print("x == 0 or x == 1")
            in 1..10 -> print("x is in the range")
            in validNumbers -> print("x is valid")
            !in 10..20 -> print("x is outside the range")
            else -> print("none of the above")//如果包含了所有的情况,就不需要写else了
        }

    fun hasPrefix(x: Any): Boolean = when (x) {
        is String -> x.startsWith("prefix")//当是string类型,则运算startsWith(),返回是否以特定前缀结尾
        else -> false//不是string类型,直接返回false
    }
    
//判断某个值是否在一个set集合里面
val items = setOf("apple", "banana", "kiwi")
        when {
            "orange" in items -> {
                println("juicy")
                println("{do something}")
            }
            "apple" in items -> {
                println("apple is fine too")
                println("do another thing!")
            }
        }
        
复制代码

8、类型转换

val e: Byte = 1
val f: Int = e.toInt()//转换
复制代码

中缀操作符 as

eg:  val x: String = y as String
val x: String? = y as String?
val x: String? = y as? String
复制代码

这里是另外一篇,入口:Kotlin初阶(2)

分类:
Android
标签:
收藏成功!
已添加到「」, 点击更改