Kotlin之美

2018年04月07日 1262点热度 0人点赞 8条评论

从2017年6月份到今年2018年的寒假,可以说已经写了大半年的Java了,小学期用Java写了三个小东西:五子棋、简易Apple Store和一个Android的拼图游戏。后来开始帮张老师写Android项目用的也是Java,其实Java带给我的感受还是挺不错的:功能强大、文档齐全,除了代码臃肿一些外我还是不排斥Java的。

和Kotlin的相遇在今年年初,是学姐的一个在搞Android开发的学长推荐的,于是抽空就了解了一下。看到别人是这样评价Kotlin的:完全兼容Java、代码极其精简、各种语法糖、可以转JavaScript(这就很有意思了),重点是:Google在去年宣布Kotlin正式称为Android官方开发语言!!听到这么多赞美它的评论不免有些心动,因此今年寒假抽空花了一下午学习了一下。这学期又花一个月用Kotlin写了大创项目,这一个多月的接触不禁让我感叹:Kotlin是世界上最好的语言!!PHP也是!!虽然网上的教程很多,但我推荐星哥给我推荐的这个learn X in Y minutes,下面来对Kotlin的语法进行一个概括:

变量声明

/* Kotlin每行的结尾不用加分号 */
val x: Int = 10   //先写变量名,再写类型,基础数据类型申明时一定要初始化
val y = 20    //数据类型可以省略,val变量只可读,无法更改
var z = "Hello World"   //var变量可以更改
var str = "z = $z, the length of z is ${z.lenght}" //在字符串中,会对$标注的变量进行解析

函数声明
/* 求和,传统写法 */
fun sum1(a: Int, b: Int): Int {
    return a + b
}

/* 当然你也可以这么写 */
fun sum2(a: Int, b: Int) = a + b

/* 如果没有返回值,可以不申明 */
fun sum3(a: Int, b: Int) {
    println(a + b)
}

/* 可变长参数 */
fun sum4(vararg x: Int) = x.sum()
sum4(1, 2, 3, 4, 5)   //调用

/* 匿名函数 */
val sum5: (Int, Int) -> Int = { a, b -> a + b }
println(sum5(1, 2))

For循环

/* 区间[0,3] */
for (i in 0..3)
    print(i)

/* 区间[0, 3) */    
for (i in 0 until 3)
    print(i)

/* 指定步长 */  
for (i in 0..3 step 2)
    print(i)

/* 反向 */
for (i in 3 downTo 0) 
    print(i)

数组
val list1 = intArrayOf(1, 2, 3)

/* 生成数组0, 1, 4, 9, 16, 25, 36 ,49, 64, 81 */
val list2 = Array(10, { i -> i * i })

val list3 = (0..9).map { it  -> 2 * it }
            .filter { it < 20 }

/* 数组值遍历 */
for (value in list1)
    print(value)

/* 数组下标遍历 */
for (index in list2.indices)
    print(index)

/* 同时获取下标和值 */
for ((index, value) in list3.withIndex())
    println("$index,$value")

条件判断

/* 简单的If用法 */
val max = if (a > b) a else b

/* when的用法 */
when(x) {
    is Int -> { print("x is Int") }
    1 -> { print("x = 1") }
    2 -> { print("x = 2") }
    3, 4 -> { print("x = 3 or 4") }
    in 0..10 { print("x is in [0, 10]") }
}

when {
    str is String -> { ... }
    a > 10 -> { ...  }
    x in list -> { ... }
}

class Person {
    var name: String = "sam"
        get() = name.toUpperCase()
        set   //什么都不写可以省略

    var id: Int = 10
        get() = field
        set(value) {
            if (value < 0)
                field = 0
            else {
                field = value
            }
        }
} 

val person = Person()
person.name = "jack"
person.id = 10

/* 构造函数 */
class Person constructor(newId: Int) {  //主构造函数
    init {      //初始化段
        println("init")
    }

    /* 属性 */
    var id = newId
    var name: String = "sam"
}

/* 主构造函数的constructor关键字可以省略 */
class Person(newId: Int) {
    init {
        println("init")
    }

    var id = newId

    var name: String = "sam"
}

/* 次构造函数 */
class Person(newId: Int) {
    init {
        println("init")
    }

    /* 次构造函数的constructor关键字不能省略, 且必须调用主构造函数 */
    constructor(newId: Int, newName: String): this(newId) {
        name = newName
    }

    var id = newId

    var name: String = "sam"
}

val person = Person(10, "Kotlin is good")


/* 继承 */
open class Father(newName: String) {  //只有用关键字open标明的类才能被继承
    var name = newName
    
    open fun speakFather() {  //可以被重写
        println(name)
    }
}
class Child(newName: String) : Father(newName) {
    override fun speakFather() {  //重写父类方法
        super.speakFather()
        println("You are so Pi")
    }
}


/* 接口 */
class Child(newName: String) : Father(newName), Listener {
    override fun speakFather() {
        super.speakFather()
        println("You are so Pi")
    }

    override fun speak() { ... }

    override fun walk() { ... }
}
interface Listener {
    fun speak()
    
    fun walk()
}

/* 数据类(相当于Java Bean,不用写get,set方法) */
data class User(val telephone: String,
                val name: String,
                val age: Int)
                
/* 枚举类 */
enum class Color {
    BLACK, WHITE, RED, GREEN, BLUE
}

空指针

写过Java的人100%都遇到过这个错误(java.lang.NullPointerException),Tony Hoare自称这是一个价值十亿美元的错误,Kotlin中,如果一个对象可能为null必须做提前声明,例如:

val x: Int = null   //编译无法通过

val x: Int? = null  //必须用问号进行标识

x?.let { println(x) }    //如果x不为null则执行let中的方法

val str = x?.toString()   //如果x为空则不执行,str的类型为String?

val fuck = x!!.toString() //如果你自己确定一定以及肯定x不为空,则用!!标识骗过编译器,但是如果真的为空,则会报NullPointerException

伴生对象

class Const {
    companion object {
        val address = "127.0.0.1"
    }
}
object Utils {
    fun md5(text: String) { ... }
}

/* 相当于Java的static对象和方法,可以直接调用 */ 
Const.address
Utils.md5("surprise mother fucker")

扩展函数

fun main(args: Array<String>) {
    val list = ArrayList<Int>()
    list.add(1)
    list.add(2)
    list.add(3)
    list.add(4)
    list.swap(0, 1)
    for (i in list)
        print(i)

}
fun ArrayList<Int>.swap(index1: Int, index2: Int) {
    val temp = this[index1]
    this[index1] = this[index2]
    this[index2] = temp
}

Plus

文章评论

  • 头像
    Justin

    Hey there :)

    Your wordpress site is very sleek - hope you don't mind me asking what theme you're
    using? (and don't mind if I steal it? :P)

    I just launched my site --also built in wordpress like yours-- but the theme slows (!) the site down quite a bit.

    In case you have a minute, you can find it by searching for "royal cbd" on Google (would appreciate
    any feedback) - it's still in the works.

    Keep up the good work-- and hope you all take care of yourself during the
    coronavirus scare!

    2020年04月01日
  • 头像
    kd 11

    It is best to take part in a contest for top-of-the-line blogs on the web. I'll suggest this site!

    2020年07月15日
  • 头像
    supreme

    You need to take part in a contest for probably the greatest blogs on the web. I will advocate this website!

    2020年07月20日
  • 头像
    golden goose sneakers

    The following time I read a weblog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my option to read, however I truly thought youd have one thing attention-grabbing to say. All I hear is a bunch of whining about one thing that you possibly can repair in case you werent too busy in search of attention.

    2020年07月22日
  • 头像
    kyrie 5

    An fascinating discussion is value comment. I think that you must write more on this topic, it won't be a taboo subject but usually people are not enough to speak on such topics. To the next. Cheers

    2020年07月24日
  • 头像
    Richard

    Thanks very interesting blog!

    2020年07月31日
  • 头像
    Donald

    Now I am going to do my breakfast, afterward having my breakfast coming yet again to read other news.

    2020年08月05日