Kotlin函数和变量

2018-05-14  本文已影响0人  FlyClound

1,函数

fun main(args: Array<String>) {
    println("Hello,world!")
}
>>> println("Hello,world!")
Hello,world!
fun max(a:Int,b:Int):Int{
    return a+b
}
>>> println(max(3,5))
8
也可以用下面两种方法声明
fun max2(a:Int,b:Int) : Int = a+b
fun max3(a: Int,b: Int) = a+b
/**
 * 比较大小,两种写法,只有表达式函数的返回值可以省略,对于有返回值的代码块体函数,必须显式的写出返回类型和return语句.
 */
fun max4(a: Int,b: Int):Int = if (a>b) a else b
fun max5(a: Int,b: Int) = if (a>b) a else b

在Kotlin中,if是表达式.语句和表达式的区别,表达式有值,并且能作为另一个表达式的一部分使用;而语句总是包围着它的代码块中的顶层元素,并且没有自己的值.在Java中,所有的控制结构都是语句.在Kotlin中,除了循环以外大多数控制结构都是表达式.

2,变量

  //变量
    val question = "The Ultimate Question of Life,the Universe,and Everything"
    val answer = 42
    val answer2 :Int = 42//同上
    //如果变量没有初始化器,需要显式地指定它的类型
    val answer3 : Int
    answer3=33
上一篇 下一篇

猜你喜欢

热点阅读