注意:不需要匹配目录和包;源文件可以放在任意目录中
package my.demo import java.util.* //为了简洁,可以这样写,返回类型kotlin会自动推算出来
fun sum(a: Int, b: Int) = a + b函数返回无意义值时,用Unit类型(相当于Java中的void),当然也可以省略不写。
fun printSum(a: Int, b: Int): Unit { println("sum of $a and $b is ${a + b}") }val 常量声明
val a: Int = 1 // 立即赋值 val b = 2 // 根据值自动推算出类型 val c: Int // 声明变量却不立即赋值时需要声明变量类型!!! c = 3 // 后续赋值操作var 变量声明
var x = 5 // `Int` type is inferred x += 1没什么可说的, 直接用 return 关键词返回值 。
fun maxOf(a: Int, b: Int): Int { if (a > b) { return a } else { return b } }也可以写成
fun maxOf(a: Int, b: Int) = if (a > b) a else b这可以说是Kotlin的语言特性之一,很好的避免了在Android开发时的空指针异常。 当一个变量可能为null时,引用必须被明确地标记为可空。跟java中的@Nullable 有点像。
fun parseInt(str: String): Int? { // ... 可能返回 Null } fun printProduct(arg1: String, arg2: String) { val x = parseInt(arg1) val y = parseInt(arg2) // 检查是否为空 if (x != null && y != null) { // 为空检查之后,x y,会被自动转换为了 非空对象(@NotNull) println(x * y) } else { println("either '$arg1' or '$arg2' is not a number") } }注意,Kotlin的世界可没有new 关键字,对象从此再也new不出来 了。
for循环 listOf可以定义一个集合。 for (item in items) 有点像Java中的for(String str : strings ) 这种写法,不过更简洁,类型都不用写。记住就好了。 val items = listOf("apple", "banana", "kiwi") for (item in items) { println(item) }或者: items.indices,可以得到所得对象的下标值。
val items = listOf("apple", "banana", "kiwi") for (index in items.indices) { println("item at $index is ${items[index]}") }用while 循环
val items = listOf("apple", "banana", "kiwi") var index = 0 while (index < items.size) { println("item at $index is ${items[index]}") index++ }when ,有点像Java的switch
fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Unknown" }原文链接:https://blog.csdn.net/a172131234/article/details/72637778