官术网_书友最值得收藏!

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. 

主站蜘蛛池模板: 逊克县| 金溪县| 紫阳县| 安义县| 双峰县| 甘谷县| 嘉峪关市| 崇文区| 阳曲县| 台东县| 库尔勒市| 盐津县| 余庆县| 望城县| 高台县| 荥经县| 嵊泗县| 秦安县| 横峰县| 扎囊县| 黄石市| 历史| 弥勒县| 石城县| 页游| 高唐县| 屯留县| 浠水县| 黔西县| 余干县| 鲜城| 铁力市| 岑溪市| 宕昌县| 张北县| 进贤县| 邵武市| 剑阁县| 庄浪县| 永登县| 高雄市|