android - kotlin语法糖

kotlin由来

JetBrains为什么开发kotlin](https://www.jianshu.com/p/ac420f727305)

华为编辑器2015年也发布了cm语言

空指针

fun demo() {
    val string1: String = "string1"  //确定的值
    val string2: String? = null				//不确定的值
    val string3: String? = "string3"
    
    println(string1.length)
    println(string2?.length) //调用函数不会报错
    println(string3?.length)
}

findViewById

when if

fun testWhen(int: Int) {
    when(int) {
        in 10 .. Int.MAX_VALUE -> println("${int} 太大了我懒得算")
        2, 3, 5, 7 -> println("${int} 是质数")
        else -> println("${int} 不是质数")
    }
}

fun main(args: Array<String>) {
    (0..10).forEach { testWhen(it) }
}

Anko

toast

https://github.com/Kotlin/anko

https://www.jianshu.com/p/fbe54654edc0

        relativeLayout {
            button("button in center") {
                textSize = sp(18).toFloat()
                onClick {
                   longToast("you click button")
                }
            }.lparams {
                centerInParent()
            }
        }

协程

https://www.jianshu.com/p/8dc8abca50e3

https://www.jianshu.com/p/40487ae860f2

三种启动方式

// 阻塞线程?
// 执行顺序?
// 更新页面 ?

​ runBlocking {
​ Log.e(“ddd”, “for_start”)
​ for (i in 0…5) {
​ Log.e(“ddd”, i.toString())
​ }
​ Log.e(“ddd”, “for_end”)
​ tv.text = “for_end”
​ }
​ Log.e(“ddd”, “runBocking外”)

/* var job = GlobalScope.launch {
Log.e(“ddd”, “for_start”)
for (i in 0…5) {
Log.e(“ddd”, i.toString())
}

​ Log.e(“ddd”, “for_end”)
​ tv.text = “GlobalScope.launch”
​ }
​ Log.e(“ddd”, “协程外”)*/

// job.cancel()

/*
GlobalScope.async {
Log.e(“ddd”, “for_start”)
for (i in 0…5) {
Log.e(“ddd”, i.toString())
}
Log.e(“ddd”, “for_end”)
tv.text = “for_end”
}
Log.e(“ddd”, “协程外”)
*/

		/*  GlobalScope.launch {
       var T = measureTimeMillis {
        val n1 = GlobalScope.async { doA() }
        val n2 = GlobalScope.async { doB() }
        val time = n1.await() + n2.await()
        Log.e("ddd", time.toString())
        }
        Log.e("ddd", T.toString())
    }*/
   
    dddd
    suspend fun doA(): Int {
    delay(4000)
    Log.e("ddd", "5555")
    return 5
}

suspend fun doB(): Int {
    delay(5000)
    Log.e("ddd", "10101010")
    return 10
}

多个任务

suspend wait

async {
    val response = URL("https://www.baidu.com").readText()
    uiThread {
        textView.text = response
    }
}

Kotlin中init代码块和构造方法以及伴生对象中代码的调用时机及执行顺序

https://blog.csdn.net/yuzhiqiang_1993/article/details/87863589

单例

object SingletonDemo

object Log {
    fun i(string: String) {
        println(string)
    }
}

fun main(args: Array<String>) {
    Log.i("test")
}

扩展

fun String.isName(): Boolean {
    if (isEmpty() || length > 10 || contains(" ")) {
        return false
    }
    val reg = Regex("^[a-zA-Z0-9\u4e00-\u9fa5]+$")
    return reg.matches(this)
}

fun String.isPassword(): Boolean {
    return length in 6..12
}

fun String.isNumber(): Boolean {
    val regEx = "^-?[0-9]+$"
    val pat = Pattern.compile(regEx)
    val mat = pat.matcher(this)

    return mat.find()
}
...

println("张三".isName())
println("123abc".isPassword())
println("123456".isNumber())

Model

class Person(var name: String = "张三",var ddd:String = "kkk")
val person = Person()
data class Column(
        var subId: String?,
        var subTitle: String?,
        var subImg: String?,
        var subCreatetime: String?,
        var subUpdatetime: String?,
        var subFocusnum: Int?,
        var lastId: String?,
        var lastMsg: String?,
        var lastType: String?,
        var lastMember: String?,
        var lastTIme: String?,
        var focus: String?,
        var subDesc: String?,
        var subLikenum: Int?,
        var subContentnum: Int?,
        var pushSet: String?
)

高阶函数

https://www.cnblogs.com/Jetictors/p/9225557.html

高阶函数应用:

inline fun debug(code: () -> Unit) {
    if (BuildConfig.DEBUG) {
        code()
    }
}

// Application 中
debug {
    Timber.plant(Timber.DebugTree())
}

TODO函数的源码

@kotlin.internal.InlineOnly
public inline fun TODO(): Nothing = throw NotImplementedError()

@kotlin.internal.InlineOnly
public inline fun TODO(reason: String): Nothing = 
throw NotImplementedError("An operation is not implemented: $reason")
// sumBy函数的源码
public inline fun CharSequence.sumBy(selector: (Char) -> Int): Int {
    var sum: Int = 0
    for (element in this) {
        sum += selector(element)
    }
    return sum
}

    val testStr = "abc"
    val sum = testStr.sumBy { it.toInt() }
    println(sum)

委托

https://www.jianshu.com/p/40487ae860f2

class DelegatePropertiesDemo {
    var content: String by Content()

    override fun toString(): String {
        return "DelegatePropertiesDemo Class"
    }
}

class Content {
    operator fun getValue(delegatePropertiesDemo: DelegatePropertiesDemo, property: KProperty<*>): String {
        return "${delegatePropertiesDemo} property '${property.name}' = 'Balalala ... ' "
    }

    operator fun setValue(delegatePropertiesDemo: DelegatePropertiesDemo, property: KProperty<*>, value: String) {
        println("${delegatePropertiesDemo} property '${property.name}' is setting value: '$value'")
    }
}

fun main(args: Array<String>) {
    val delegatePropertiesDemo = DelegatePropertiesDemo()
    println(delegatePropertiesDemo.content)

    delegatePropertiesDemo.content = "abc"
}

参考文档:
Kotlin中最常用的80个关键字

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值