- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 257字
- 2021-06-24 14:13:35
Defining functions
A function is a reusable piece of code, given a name, that accepts zero or more inputs and optionally returns a value. Functions are defined by using the fun keyword with optional parameters and a return value. The parameter list must always be present, even if no parameters are defined. For example, this function has no parameters and it returns a hello world value:
fun hello() : String = "hello world"
Each parameter is in the name: type form. The following function accepts two parameters of the String type and also returns a String value. In this case, the returned value is the hello to you string followed by the input parameters:
fun hello(name: String, location: String): String = "hello to you $name at $location"
If a function does not return any meaningful value, then it will return Unit. As discussed in Chapter 2, Kotlin Basics, Unit is analogous to the Java and C void types. By using a class that is part of a type hierarchy – rather than a special type, such as void – the type system in Kotlin can be made to be more regular. Every function must return a value, and this value could be Unit.
The following two function declarations are equivalent to each other:
fun print1(str: String): Unit { println(str) } fun print2(str: String) { println(str) }
Functions returning Unit can omit the return type for a procedure-style syntax if the developer wishes to do so.
- PyTorch自動駕駛視覺感知算法實戰(zhàn)
- 小創(chuàng)客玩轉圖形化編程
- Production Ready OpenStack:Recipes for Successful Environments
- React.js Essentials
- Java Web程序設計
- Node.js Design Patterns
- Nginx Lua開發(fā)實戰(zhàn)
- Learning YARN
- Python Machine Learning Blueprints:Intuitive data projects you can relate to
- 從Excel到Python數據分析:Pandas、xlwings、openpyxl、Matplotlib的交互與應用
- Python一行流:像專家一樣寫代碼
- Android嵌入式系統(tǒng)程序開發(fā)(基于Cortex-A8)
- Joomla!Search Engine Optimization
- C#網絡編程高級篇之網頁游戲輔助程序設計
- Python繪圖指南:分形與數據可視化(全彩)