Kotlin汇总1

Android官方开始支持kotlin了,可以看下Android Announces Support for Kotlin。学习kotlin的优势是非常明显的,首先Android studio是基于intellij idea开发的,Google也开始把kotlin作为Android的标准开发语言。

对于Android开发者来说,学习kotlin是非常容易的事情,很平滑的过渡。旧代码Java新代码kotlin,是不是很神奇,而且学会了kotlin,可以做如下事情:
这里写图片描述

如果英文还行的话,可以直接通过官网学习,现在也有很多中文翻译过的学习。

当然kotlin和Java还是有些不一样的地方。写这篇博客也是给自己的学习过程,以节点的方式汇总。

kotlin是推断语言,可以通过推断a是Int类型。

var a = 3 // a被编译器自动推断为Int类型

直接自动转换类型

fun getStringLength(obj: Any): Int? {
    if (obj is String) {
        // `obj` is automatically cast to `String` in this branch
        return obj.length//obj自动转换成String类型
    }

    // `obj` is still of type `Any` outside of the type-checked branch
    return null
}

kotlin是强语言,可以很好的避免空指针报错

var a: String?
a.length()//编译器会报错,因为a有可能是空指针,是不是很强大,编译器直接告诉你可能出现的空指针。

if not null的用法

val files = File("Test").listFiles()

println(files?.size)//等同于下面的效果
if(files != null){
    println(files.size)
}

If not null and else的用法

val files = File("Test").listFiles()

println(files?.size ?: "empty")//等同于下面的效果
if(files != null){
    println(files.size)
}else{
    println("empty")
}

if null执行语句

val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")//等同于下面效果

if(data["email"] == null) {
    throw IllegalStateException("Email is missing!")
}

if not null执行语句

val data = ...

data?.let {
    ... // execute this block if not null
}//等同于下面效果

if(data != null) {
    ...//execute this block if not null
}

又比如:

val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // `b` is false or null,这样是不是很方便,如果是Java处理起来会很麻烦。
}

Kotlin支持下面定义

Decimals: 123
Longs are tagged by a capital L: 123L
Hexadecimals: 0x0F
Binaries: 0b00001011
//不支持8进制

可以这样定义方法:

fun sum(a: Int, b: Int) = a + b//因为方法很简单,可以直接写到一行

也可以通过when关键字来定义方法

fun describe(obj: Any): String =
when (obj) {
    1          -> "One"
    "Hello"    -> "Greeting"
    is Long    -> "Long"
    !is String -> "Not a string"
    else       -> "Unknown"
}

可以这样使用range来做for循环

for (x in 1..5) {//1-5做循环
    print(x)
}

除了这个例子,还会很多精巧的地方,比如

fun main(args: Array<String>) {
    for (x in 1..10 step 2) { //从1到10,每步是2
        println(x)
    }
    for (x in 9 downTo 0 step 3) {// 9到0,每步是3
        println(x)
    }
}

定义一个list列表

val items = listOf("apple", "banana", "kiwi")//listOf是内置函数

定义一个map映射

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

kotlin支持lambda函数编程,想想下面的语句如果是java代码要写多少行。

fun main(args: Array<String>) {
    val fruits = listOf("banana", "avocado", "apple", "kiwi")
    fruits
    .filter { it.startsWith("a") }//过滤掉不是a开头的单词
    .sortedBy { it }//排序
    .map { it.toUpperCase() }//单词变为大写,比如:apple变为APPLE
    .forEach { println(it) }//forEach循环
}

因为kotlin没有extension关键字,但是你可以通过下面方法对内置类进行扩展

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

在类和继承方面,需要注意,因为kotlin遵循的是Effective Java原则,所以所有的kotlin类都是final类型,如果要使得这个类能被继承,那么需要加上open关键字

open class Base {
    open fun v() {}
    fun nv() {}
}
class Derived() : Base() {
    override fun v() {}
}

另外继承的超类和实现的接口出现了同样的方法名,那么这个方法必须被复写,而复写一定要显性的加上override关键字

open class A {
    open fun f() { print("A") }
    fun a() { print("a") }
}

interface B {
    fun f() { print("B") } // interface members are 'open' by default
    fun b() { print("b") }
}

class C() : A(), B {
    // The compiler requires f() to be overridden:
    override fun f() {
        super<A>.f() // call to A.f()
        super<B>.f() // call to B.f()
    }
}

抽象类默认是open的,所以不用显性加上open关键字

open class Base {
    open fun f() {}
}

abstract class Derived : Base() {
    override abstract fun f()
}

今天就汇总到这了,下篇继续。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值