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

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. 

主站蜘蛛池模板: 正宁县| 布尔津县| 德格县| 清河县| 弥勒县| 富阳市| 丰宁| 禄丰县| 桐柏县| 商洛市| 汾阳市| 巴林左旗| 色达县| 鄂托克前旗| 定远县| 石渠县| 黑龙江省| 永康市| 中山市| 永仁县| 盐池县| 绥中县| 乐昌市| 比如县| 阿瓦提县| 孙吴县| 通山县| 舞阳县| 山东省| 乐昌市| 富锦市| 海林市| 丹寨县| 兴义市| 田林县| 十堰市| 南陵县| 将乐县| 卢湾区| 凤山市| 宜良县|