《Kotlin极简教程》第二章 Hello,World 函数

来源:互联网 发布:定格动画软件 编辑:程序博客网 时间:2024/06/13 17:24

最新上架!!!
《 Kotlin极简教程》 陈光剑 (机械工业出版社):
https://mp.weixin.qq.com/s/bzRkGSO6T1O2AELM_UqKUQ

此开篇第二回。

直接来说: Hello,World!

HelloWorld.kt

/** * We declare a package-level function main which returns Unit and takes * an Array of strings as a parameter. Note that semicolons are optional. */fun main(args: Array<String>) {    println("Hello, world!")}

函数

函数声明

在Kotlin中,函数声明使用关键字 fun

fun double(x: Int): Int {}

函数调用

调用函数使用传统的方法

val result = double(2)

更多示例

带有两个 Int 参数、返回 Int的函数:

fun sum(a: Int, b: Int): Int { return a + b}

将表达式作为函数体、返回值类型自动推断的函数:

fun sum(a: Int, b: Int) = a + b

函数返回无意义的值:

fun printSum(a: Int, b: Int): Unit { print(a + b)}

Unit返回类型可以省略:

fun printSum(a: Int, b: Int) { print(a + b)}
阅读全文
1 0