- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 206字
- 2021-06-10 18:49:21
When clause
when is a pattern matching clause in Kotlin. This helps us to write elegant code when dealing with pattern matching, meaning we can avoid using a lot of if else statements.
Let's write a function that takes an input, the type of which is not known. Any is used to indicate this and a when block is used to handle different patterns.
Consider the code for 10_when.kts:
fun processInput(input: Any) {
when(input) {
10 -> println("It is 10")
98,99 -> println("It is 98 or 99")
in 101 .. 120 -> println("More than 100")
is String -> println("This is ${input} of length ${input.length}")
else -> println("Not known")
}
}
processInput(10)
processInput(98)
processInput(99)
processInput(102)
processInput("hey there")
processInput(Thread())
The output is as follows:
Alongside the pattern matching, we can also perform type checking using the when block:
is String -> println("This is ${input} of length ${input.length}")
Note that the argument input is of the Any type. After type checking, the input is automatically cast to String, and we can use the length property, which is defined in the String class. The Kotlin language does the auto-typecasting for us, so we don't have to do any explicit type casting.
- Java多線程編程實(shí)戰(zhàn)指南:設(shè)計(jì)模式篇(第2版)
- Docker and Kubernetes for Java Developers
- Effective C#:改善C#代碼的50個(gè)有效方法(原書(shū)第3版)
- JavaScript:Functional Programming for JavaScript Developers
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- Java虛擬機(jī)字節(jié)碼:從入門(mén)到實(shí)戰(zhàn)
- Learning Neo4j 3.x(Second Edition)
- Android Native Development Kit Cookbook
- SQL Server與JSP動(dòng)態(tài)網(wǎng)站開(kāi)發(fā)
- Python爬蟲(chóng)、數(shù)據(jù)分析與可視化:工具詳解與案例實(shí)戰(zhàn)
- 響應(yīng)式Web設(shè)計(jì):HTML5和CSS3實(shí)戰(zhàn)(第2版)
- Citrix XenServer企業(yè)運(yùn)維實(shí)戰(zhàn)
- 后臺(tái)開(kāi)發(fā):核心技術(shù)與應(yīng)用實(shí)踐
- Mastering PowerCLI
- HTML5游戲開(kāi)發(fā)實(shí)戰(zhàn)