# 基本语法

## 定义包

``````package my.demo

import java.util.*

// ……``````

## 定义函数

``````//sampleStart
fun sum(a: Int, b: Int): Int {
return a + b
}
//sampleEnd

fun main() {
print("sum of 3 and 5 is ")
println(sum(3, 5))
}``````

``````//sampleStart
fun sum(a: Int, b: Int) = a + b
//sampleEnd

fun main() {
println("sum of 19 and 23 is \${sum(19, 23)}")
}``````

``````//sampleStart
fun printSum(a: Int, b: Int): Unit {
println("sum of \$a and \$b is \${a + b}")
}
//sampleEnd

fun main() {
printSum(-1, 8)
}``````

`Unit` 返回类型可以省略：

``````//sampleStart
fun printSum(a: Int, b: Int) {
println("sum of \$a and \$b is \${a + b}")
}
//sampleEnd

fun main() {
printSum(-1, 8)
}``````

## 定义变量

``````fun main() {
//sampleStart
val a: Int = 1  // 立即赋值
val b = 2   // 自动推断出 `Int` 类型
val c: Int  // 如果没有初始值类型不能省略
c = 3       // 明确赋值
//sampleEnd
println("a = \$a, b = \$b, c = \$c")
}``````

``````fun main() {
//sampleStart
var x = 5 // 自动推断出 `Int` 类型
x += 1
//sampleEnd
println("x = \$x")
}``````

``````//sampleStart
val PI = 3.14
var x = 0

fun incrementX() {
x += 1
}
//sampleEnd

fun main() {
println("x = \$x; PI = \$PI")
incrementX()
println("incrementX()")
println("x = \$x; PI = \$PI")
}``````

## 注释

``````// 这是一个行注释

/* 这是一个多行的
块注释。 */``````

## 使用字符串模板

``````fun main() {
//sampleStart
var a = 1
// 模板中的简单名称：
val s1 = "a is \$a"

a = 2
// 模板中的任意表达式：
val s2 = "\${s1.replace("is", "was")}, but now is \$a"
//sampleEnd
println(s2)
}``````

## 使用条件表达式

``````//sampleStart
fun maxOf(a: Int, b: Int): Int {
if (a > b) {
return a
} else {
return b
}
}
//sampleEnd

fun main() {
println("max of 0 and 42 is \${maxOf(0, 42)}")
}``````

``````//sampleStart
fun maxOf(a: Int, b: Int) = if (a > b) a else b
//sampleEnd

fun main() {
println("max of 0 and 42 is \${maxOf(0, 42)}")
}``````

## 使用可空值及 null{: .keyword } 检测

``````fun parseInt(str: String): Int? {
// ……
}``````

``````fun parseInt(str: String): Int? {
return str.toIntOrNull()
}

//sampleStart
fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)

// 直接使用 `x * y` 会导致编译错误，因为他们可能为 null
if (x != null && y != null) {
// 在空检测后，x 与 y 会自动转换为非空值（non-nullable）
println(x * y)
}
else {
println("either '\$arg1' or '\$arg2' is not a number")
}
}
//sampleEnd

fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("a", "b")
}``````

``````fun parseInt(str: String): Int? {
return str.toIntOrNull()
}

fun printProduct(arg1: String, arg2: String) {
val x = parseInt(arg1)
val y = parseInt(arg2)

//sampleStart
// ……
if (x == null) {
println("Wrong number format in arg1: '\$arg1'")
return
}
if (y == null) {
println("Wrong number format in arg2: '\$arg2'")
return
}

// 在空检测后，x 与 y 会自动转换为非空值
println(x * y)
//sampleEnd
}

fun main() {
printProduct("6", "7")
printProduct("a", "7")
printProduct("99", "b")
}``````

## 使用类型检测及自动类型转换

is{: .keyword } 运算符检测一个表达式是否某类型的一个实例。

``````//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj is String) {
// `obj` 在该条件分支内自动转换成 `String`
return obj.length
}

// 在离开类型检测分支后，`obj` 仍然是 `Any` 类型
return null
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("'\$obj' string length is \${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}``````

``````//sampleStart
fun getStringLength(obj: Any): Int? {
if (obj !is String) return null

// `obj` 在这一分支自动转换为 `String`
return obj.length
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("'\$obj' string length is \${getStringLength(obj) ?: "... err, not a string"} ")
}
printLength("Incomprehensibilities")
printLength(1000)
printLength(listOf(Any()))
}``````

``````//sampleStart
fun getStringLength(obj: Any): Int? {
// `obj` 在 `&&` 右边自动转换成 `String` 类型
if (obj is String && obj.length > 0) {
return obj.length
}

return null
}
//sampleEnd

fun main() {
fun printLength(obj: Any) {
println("'\$obj' string length is \${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")
}
printLength("Incomprehensibilities")
printLength("")
printLength(1000)
}``````

## 使用 `for` 循环

``````fun main() {
//sampleStart
val items = listOf("apple", "banana", "kiwifruit")
for (item in items) {
println(item)
}
//sampleEnd
}``````

``````fun main() {
//sampleStart
val items = listOf("apple", "banana", "kiwifruit")
for (index in items.indices) {
println("item at \$index is \${items[index]}")
}
//sampleEnd
}``````

## 使用 `while` 循环

``````fun main() {
//sampleStart
val items = listOf("apple", "banana", "kiwifruit")
var index = 0
while (index < items.size) {
println("item at \$index is \${items[index]}")
index++
}
//sampleEnd
}``````

## 使用 `when` 表达式

``````//sampleStart
fun describe(obj: Any): String =
when (obj) {
1          -> "One"
"Hello"    -> "Greeting"
is Long    -> "Long"
!is String -> "Not a string"
else       -> "Unknown"
}
//sampleEnd

fun main() {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
}``````

## 使用区间（range）

``````fun main() {
//sampleStart
val x = 10
val y = 9
if (x in 1..y+1) {
println("fits in range")
}
//sampleEnd
}``````

``````fun main() {
//sampleStart
val list = listOf("a", "b", "c")

if (-1 !in 0..list.lastIndex) {
println("-1 is out of range")
}
if (list.size !in list.indices) {
println("list size is out of valid list indices range, too")
}
//sampleEnd
}``````

``````fun main() {
//sampleStart
for (x in 1..5) {
print(x)
}
//sampleEnd
}``````

``````fun main() {
//sampleStart
for (x in 1..10 step 2) {
print(x)
}
println()
for (x in 9 downTo 0 step 3) {
print(x)
}
//sampleEnd
}``````

## 使用集合

``````fun main() {
val items = listOf("apple", "banana", "kiwifruit")
//sampleStart
for (item in items) {
println(item)
}
//sampleEnd
}``````

``````fun main() {
val items = setOf("apple", "banana", "kiwifruit")
//sampleStart
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
//sampleEnd
}``````

``````fun main() {
//sampleStart
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits
.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.toUpperCase() }
.forEach { println(it) }
//sampleEnd
}``````

## 创建基本类及其实例：

``````fun main() {
//sampleStart
val rectangle = Rectangle(5.0, 2.0) // 不需要“new”关键字
val triangle = Triangle(3.0, 4.0, 5.0)
//sampleEnd
println("Area of rectangle is \${rectangle.calculateArea()}, its perimeter is \${rectangle.perimeter}")
println("Area of triangle is \${triangle.calculateArea()}, its perimeter is \${triangle.perimeter}")
}

abstract class Shape(val sides: List<Double>) {
val perimeter: Double get() = sides.sum()
abstract fun calculateArea(): Double
}

interface RectangleProperties {
val isSquare: Boolean
}

class Rectangle(
var height: Double,
var length: Double
) : Shape(listOf(height, length, height, length)), RectangleProperties {
override val isSquare: Boolean get() = length == height
override fun calculateArea(): Double = height * length
}

class Triangle(
var sideA: Double,
var sideB: Double,
var sideC: Double
) : Shape(listOf(sideA, sideB, sideC)) {
override fun calculateArea(): Double {
val s = perimeter / 2
return Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC))
}
}``````