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

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. 

主站蜘蛛池模板: 新密市| 东港市| 仁布县| 陆良县| 招远市| 崇文区| 大洼县| 洪泽县| 苏尼特右旗| 晴隆县| 济宁市| 临江市| 永修县| SHOW| 喀喇| 亳州市| 博野县| 汕头市| 达尔| 茌平县| 五莲县| 张家口市| 丽水市| 玉山县| 揭阳市| 塘沽区| 祁阳县| 沂源县| 句容市| 苏尼特左旗| 江华| 庆元县| 平乐县| 沽源县| 鄄城县| 西吉县| 彝良县| 邹平县| 富顺县| 三门峡市| 怀远县|