Kotlin那些实用的语法糖

2018-05-18  本文已影响0人  b2d187b56305

使用with、apply、run简化代码,增强可读性

         //原始
        task_viewpager.setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL)
        task_viewpager.adapter = SentenceAdapter(taskList)
        task_viewpager.currentItem = index

        //apply
        task_viewpager.apply {
            setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL)
            adapter = SentenceAdapter(taskList)
            currentItem = index
        }

        //with
        with(task_viewpager){
            setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL)
            adapter = SentenceAdapter(taskList)
            currentItem = index
        }

        //run
        index = task_viewpager.run {
            setScrollMode(UltraViewPager.ScrollMode.HORIZONTAL)
            adapter = SentenceAdapter(taskList)
            currentItem
        }

        

相比较而言使用apply更符合链式编程的习惯
run函数具有表达式的,它返回最后一行的值

其他函数

val input = Files.newInputStream(Paths.get("input.txt"))
val byte = input.use({ input.read() })
repeat(10, { println("Hello") })
require(true,{"error message"})

空指针处理,避免长串!!出现

val user = User()
    user!!.name!!.subSequence(0,5)!!.length

val user: User? = User()

    //每次访问都用用?.判断
    user?.name
    user?.age
    user?.toString()

//提前判断非空
if (user != null) {
        user.name
        user.age
        user.toString()
    }
//let语句
user?.let {
        it.name
        it.age
        it.toString()
    }

扩展函数

fun Activity.toast(msg:String, duration:Int = Toast.LENGTH_SHORT){
    Toast.makeText(this,msg,duration)
}

fun Fragment.toast(msg:String, duration:Int = Toast.LENGTH_SHORT){
    Toast.makeText(activity,msg,duration)
}

toast("123")

上一篇 下一篇

猜你喜欢

热点阅读