- 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.
- Mobile Web Performance Optimization
- Vue.js入門與商城開發實戰
- Python Deep Learning
- 精通Python自然語言處理
- C# 8.0核心技術指南(原書第8版)
- Node.js Design Patterns
- Solr Cookbook(Third Edition)
- 計算機應用基礎教程(Windows 7+Office 2010)
- Visual Basic程序設計習題與上機實踐
- Beginning C++ Game Programming
- Getting Started with Nano Server
- Swift語言實戰晉級
- Advanced UFT 12 for Test Engineers Cookbook
- Django Design Patterns and Best Practices
- Docker:容器與容器云(第2版)