- 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.
- Django+Vue.js商城項目實戰
- Building a RESTful Web Service with Spring
- MongoDB for Java Developers
- Python進階編程:編寫更高效、優雅的Python代碼
- 深入淺出Android Jetpack
- 零基礎學MQL:基于EA的自動化交易編程
- Mastering Drupal 8 Views
- Mastering openFrameworks:Creative Coding Demystified
- 持續輕量級Java EE開發:編寫可測試的代碼
- Vue.js 2 Web Development Projects
- Kivy Cookbook
- Learning Hadoop 2
- 軟件測試綜合技術
- Delphi開發典型模塊大全(修訂版)
- Mastering Gephi Network Visualization