- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 209字
- 2021-06-24 14:13:35
Single expression functions
Usually, a function must declare its return type; an exception exists only for functions that consist of a single expression. These are often referred to as one line or single line functions. Such functions can use a shortened syntax that omits the braces and uses the = symbol before the expression rather than the return keyword:
fun square(k: Int) = k * k
You can see how the function does not need to declare the return value of Int. This is inferred by the compiler. The rationale behind this feature is that very short functions are easy to read, and the return value is a bit of extra noise that doesn't add much to the overall process. However, you can always include the return value if you think that it makes things clearer:
fun square2(k: Int): Int = k * k
Single expression functions can always be written in the regular style if desired. For example, the following two functions are identical and are compiled to the same bytecode:
fun concat1(a: String, b: String) = a + b fun concat2(a: String, b: String): String { return a + b }
- Python 3.7網(wǎng)絡(luò)爬蟲快速入門
- ThinkPHP 5實戰(zhàn)
- 兩周自制腳本語言
- 編程卓越之道(卷3):軟件工程化
- Java高手真經(jīng)(高級編程卷):Java Web高級開發(fā)技術(shù)
- The React Workshop
- Python高級編程
- Designing Hyper-V Solutions
- Angular開發(fā)入門與實戰(zhàn)
- Cocos2d-x Game Development Blueprints
- 鴻蒙OS應(yīng)用編程實戰(zhàn)
- Illustrator CS6設(shè)計與應(yīng)用任務(wù)教程
- Django Design Patterns and Best Practices
- Java Hibernate Cookbook
- Python數(shù)據(jù)可視化之matplotlib實踐