空语句

Kotlin 语言中的空语句有

  • {}
  • Unit
when (x) {
1 -> ...
2 -> ...
else -> {}
// else -> Unit
}

When 表达式

使用不带判断条件的 when 表达式来改写多路分支

val v = if (x < y) 1 else if (x == y) 2 else 3

val v = when {
x < y -> 1
x == y -> 2
else -> 3
}

使用带判断条件的 when 表达式来模拟模式匹配

val v = if (x == 1) 1 else if (x == 2) 3 else 5

val v = when (x) {
1 -> 1
2 -> 3
else -> 5
}

?. 与 ?:

// n的值为a,b,c,4当中第一个不是null的数
val n = a ?: b ?: c ?: 4
a b c n
1 / / 1
null 2 / 2
null null 3 3
null null null 4
// n的值为a.b.c,条件是a,a.b,a.b.c都不是null。否则n的值为4。
val n = a?.b?.c ?: 4
a a.b a.b.c n
null / / 4
!= null null / 4
!= null != null null 4
!= null != null 3 3

使用解构声明来声明两个带值的变量

var (a, b) = listOf(1, 2) // a == 1, b == 2
var (a, b) = Pair(1, 2) // a == 1, b == 2
var (a, b) = 1 to 2 // a == 1, b == 2

let

the tldr; on Kotlin’s let, apply, also, with and run functions

// Calls the specified function [block] with `this` value as its argument and returns its result.
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

调用代码块,代码块中调用方 this 为参数 it,返回代码块的结果。

// using 'let' to convert from one type to another
val answerToUniverse = strBuilder.let {
it.append("Douglas Adams was right after all")
it.append("Life, the Universe and Everything")
42
}
// using 'let' to only print when str is not null
str?.let { print(it) }

apply

// Calls the specified function [block] with `this` value as its receiver and returns `this` value.
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

调用代码块,代码块中调用方 this 为隐式调用方 receiver,返回调用方 this。

// old way of building an object
val andre = Person()
andre.name = "andre"
andre.company = "Viacom"
andre.hobby = "losing in ping pong"
// after applying 'apply' (pun very much intended)
val andre = Person().apply {
name = "Andre"
company = "Viacom"
hobby = "losing in ping pong"
}

also

// Calls the specified function [block] with `this` value as its argument and returns `this` value.
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

调用代码块,代码块中调用方 this 为参数 it,返回调用方 this 。

// transforming data from api with intermediary variable
val rawData = api.getData()
Log.debug(rawData)
rawData.map { /** other stuff */ }
// use 'also' to stay in the method chains
api.getData()
.also { Log.debug(it) }
.map { /** other stuff */ }

with

// Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

调用代码块,代码块中指定参数为隐式调用方 receiver,返回代码块的结果。

// Every Android Developer ever after Wednesday May 17th 2017
messageBoard.init(“https://url.com”)
messageBoard.login(token)
messageBoard.post("Kotlin’s a way of life bro") // using 'with' to avoid repetitive references to identifier
with(messageBoard) {
init(“https://url.com”)
login(token)
post(“Kotlin’s a way of life bro")
}

run

// Calls the specified function [block] with `this` value as its receiver and returns its result.
public inline fun <T, R> T.run(block: T.() -> R): R = block()

调用代码块,代码块中调用方 this 为隐式调用方 receiver,返回代码块的结果。

// GoT developers after season 7
aegonTargaryen = jonSnow.run {
makeKingOfTheNorth()
swearsFealtyTo(daenerysTargaryen)
realIdentityRevealed(“Aegon Targaryen”)
}

let, apply, also, with & run

代码块/函数 let apply also with run
参数或调用方 this 为隐式调用方 receiver
调用方 this 为参数 it
返回调用方 this
返回代码块的结果

takeIf / takeUnless

difference between kotlin also, apply, let, use, takeIf and takeUnless in Kotlin

// Returns this value if it satisfies the given predicate or null, if it doesn't.
inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
// Returns this value if it does not satisfy the given predicate or null, if it does.
inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null

takeIf:调用方 this 如果符合某个条件则返回调用方 this,否则返回 null。

takeUnless:调用方 this 如果不符合某个条件则返回调用方 this,否则返回 null。

println(myVar.takeIf { it is Person } ?: "Not a person!")
println(myVar.takeUnless { it is Person } ?: "It's a person!")

Kotlin语言编程技巧集的更多相关文章

  1. 一些有意思的面试题(持续更新) .C语言编程技巧札记

    一些有意思的面试题(持续更新) http://blog.csdn.net/wangyuling1234567890/article/details/38565239 C语言编程技巧札记 http:// ...

  2. C语言编程技巧-signal(信号)[转]

    自 http://www.uml.org.cn/c++/200812083.asp 信号是Linux编程中非常重要的部分,本文将详细介绍信号机制的基本概念.Linux对信号机制的大致实现方法.如何使用 ...

  3. 用Kotlin语言重新编写Plaid APP:经验教训(I)

    原文标题:Converting Plaid to Kotlin: Lessons learned (Part 1) 原文链接:http://antonioleiva.com/plaid-kotlin- ...

  4. 15个提高编程技巧的JavaScript工具

    原文地址:http://www.imooc.com/wenda/detail/243523 JavaScript脚本库是一个预先用JavaScript语言写好的库,它方便了我们开发基于JavaScri ...

  5. BASH的保护性编程技巧

    BASH的保护性编程技巧   shell常用逻辑判断 -b file 若文件存在且是一个块特殊文件,则为真 -c file 若文件存在且是一个字符特殊文件,则为真 -d file 若文件存在且是一个目 ...

  6. 安卓开发(2)—— Kotlin语言概述

    安卓开发(2)-- Kotlin语言概述 Android的官方文档都优先采用Kotlin语言了,学它来进行Android开发已经是一种大势所趋了. 这里只讲解部分的语法. 如何运行Kotlin代码 这 ...

  7. 释放Android的函数式能量(I):Kotlin语言的Lambda表达式

    原文标题:Unleash functional power on Android (I): Kotlin lambdas 原文链接:http://antonioleiva.com/operator-o ...

  8. linux 操作系统下c语言编程入门

    2)Linux程序设计入门--进程介绍 3)Linux程序设计入门--文件操作 4)Linux程序设计入门--时间概念 5)Linux程序设计入门--信号处理 6)Linux程序设计入门--消息管理  ...

  9. Kotlin 语言高级安卓开发入门

    过去一年,使用 Kotlin 来为安卓开发的人越来越多.即使那些现在还没有使用这个语言的开发者,也会对这个语言的精髓产生共鸣,它给现在 Java 开发增加了简单并且强大的范式.Jake Wharton ...

随机推荐

  1. SCCM2012 R2实战系列之九:OSD(中)--捕获镜像

    在上篇文章中我们详细的完成了OSD的初始化配置.导入镜像.任务序列的创建和常见问题的排错.但是在实际环境中这样分发了干净的操作系统后还需要手动为客户端安装各种各样的应用程序.所以更为好的方法是将一台计 ...

  2. Mybatis 系列3-结合源码解析properties节点和environments节点

    [Mybatis 系列10-结合源码解析mybatis 执行流程] [Mybatis 系列9-强大的动态sql 语句] [Mybatis 系列8-结合源码解析select.resultMap的用法] ...

  3. 数据分箱:等频分箱,等距分箱,卡方分箱,计算WOE、IV

    转载:https://zhuanlan.zhihu.com/p/38440477 转载:https://blog.csdn.net/starzhou/article/details/78930490 ...

  4. linux 高级路由

    1. 什么是高级路由? 是把信息从源穿过网络到达目的地的行为. 有两个动作:确定最佳路径,传输信息 确定最佳路径:手工指定,自动学习. 传输信息:隧道传输,流量整形 高级路由(策略路由)是根据一定的需 ...

  5. tp3.2sql改变时间格式

    tp3.2sql改变时间格式2018-05-10取05-10 $listIn=D('api_article as a')->field('date_format( fabutime,\'%m-% ...

  6. linux下mysql-5.6忘记root密码,重置root密码详细过程

      在linux平台下使用mysql过程中忘记了root密码,对于运维和DBA来讲都是一件头疼的事情,下面来讲解下怎么进行重置mysql数据库root 密码: 1.首先停止mysql服务进程: 1 s ...

  7. java的list遍历

    for(String str : list) {//增强for循环,其内部实质上还是调用了迭代器遍历方式,这种循环方式还有其他限制,不建议使用. System.out.println(str); } ...

  8. shell 的有用函数

    1.isNumber 2.命令可用 3.当前用户是root 1.isNumber 判断“字符串”是否是个数字: declare chkNumber= isNumber(){ parameter1=$ ...

  9. iar stm32 启动代码片段分析

    今天查看了 iar 上面的启动文件,好奇堆栈指针到底是什么时候赋值的,所以就仔细的阅读了代码和相关手册,找到了答案. 首先,芯片启动后,会从ROM的首地址处进行执行,那么我们从 linker 里面找找 ...

  10. scp(secure copy)安全拷贝

    scp(secure copy)安全拷贝 (1)scp定义: scp可以实现服务器与服务器之间的数据拷贝.(from server1 to server2) (2)基本语法 命令  递归  要拷贝的文 ...