- 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實現)
- 劍指MySQL:架構、調優與運維
- Protocol-Oriented Programming with Swift
- HTML5移動前端開發基礎與實戰(微課版)
- Web前端開發最佳實踐
- Instant GLEW
- Web開發新體驗
- INSTANT Lift Web Applications How-to
- C++從零開始學(視頻教學版)(第2版)
- Puppet Cookbook(Third Edition)
- Visual Basic 開發從入門到精通
- C#入門經典(第7版):C# 6.0 & Visual Studio 2015(.NET開發經典名著)
- Nginx Troubleshooting
- NLTK Essentials
- Erlang編程指南