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

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. 

主站蜘蛛池模板: 略阳县| 湘阴县| 保康县| 高雄县| 华宁县| 准格尔旗| 华亭县| 大方县| 资阳市| 延长县| 龙游县| 福建省| 改则县| 弋阳县| 昭通市| 林芝县| 察哈| 多伦县| 股票| 高雄县| 环江| 苍梧县| 乐平市| 阿合奇县| 英德市| 探索| 南涧| 永和县| 福清市| 明光市| 宁武县| 宁国市| 大名县| 嘉荫县| 西城区| 黄浦区| 上犹县| 平遥县| 廊坊市| 罗源县| 灵寿县|