在代码中学习 Kotlin 基本语法

一、基本语法

fun main(args: Array) {

    // 定义变量
    // 定义不可变变量
    val a: Int = 1 // 直接赋值
    val b = 2 // 不指定类型,b 被推断为 int 类型
    val c: Int // 只定义不初始化需要制定变量的类型
    c = 3 // 为变量赋值
    // val 定义的变量的值不可更改

    // 定义可变变量
    var d = 4;
    d = a + b;


    // 字符串
    var aa = 1
    // 在字符串中使用变量的值
    var s1 = "aa is $aa"
    aa = 4
    // 在字符串中进行运算
    var s2 = "${s1.replace("is", "was")}, but now is $aa"


    // 创建类的实例
    val rectangle = Rectangle(5.0, 2.0)
    val triangle = Triangle(3.0, 4.0, 5.0)
    println("Area of rectangle is ${rectangle.calculateArea()}, its perimeter is ${rectangle.perimeter}")
    println("Area of triangle is ${triangle.calculateArea()}, its perimeter is ${triangle.perimeter}")
}


// 定义方法
/**
 * 定义方法的格式:
 * fun 方法名(参数: 参数类型, ...): 返回值类型 {
 *     // 此处为方法体
 * }
 * // 无返回值时,返回值类型可以写:Unit 也可以省略
 *
 */
// 常见写法
fun sum1(a: Int, b: Int): Int {
    return a + b
}

// 当方法体只有1句话的时候可以这么写
fun sum2(a: Int, b: Int) = a + b


// if 条件语句
fun maxOf(a: Int, b: Int): Int {
    if (a > b) {
        return a
    } else {
        return b
    }
}

// 还可以写成如下形式
fun maxOf1(a: Int, b: Int) = if (a > b) a else b


// 类型检测和动态类型转换
// 写法1
fun getStringLength(obj: Any): Int? {
    // 类型检测
    if (obj is String) {
        return obj.length
    }
    return null
}

// 写法2
fun getStringLength1(obj: Any): Int? {
    if (obj !is String) {
        return null
    }
    return obj.length
}

// 写法3
fun getStringLength2(obj: Any): Int? {
    if (obj is String && obj.length > 0) {
        return obj.length
    }
    return null
}


// 循环语句,定义在方法内,方便直接在 main 中调用查看输出情况
fun loop() {
    // for 循环
    val items = listOf("apple", "banana", "kiwifruit")
    // 写法1
    for (item in items) {
        println(item)
    }

    // 写法2
    for (index in items.indices) {
        println("item as $index is ${items[index]}")
    }

    // while 循环
    var index = 0
    while (index < items.size) {
        println("item at $index is ${items[index]}")
        index++
    }
}


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


// 使用范围 (ranges)
fun ranges() {
    val x = 10
    val y = 9
    // 检查某个值是否在一个范围内
    if (x in 1..y+1) {
        println("fits in range")
    }

    // 检查某个值是否在一个范围外
    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")
    }

    // 遍历一个范围
    for(x in 1..5) {
        println(x)
    }
    println()

    // 遍历范围时指定步长
    // 遍历1到10每隔2打印x
    for (x in 1..10 step 2) {
        println(x)
    }
    println()
    // 遍历9到0每隔3打印x
    for (x in 9 downTo 0 step 3) {
        println(x)
    }
}


// 使用集合
fun collections() {
    val items = listOf("apple", "banana", "orange", "abc")
    // 遍历集合
    for (item in items) {
        println(item)
    }
    println()

    // 判断集合是否包含某个对象
    when {
        "aa" in items -> println("juicy")
        "apple" in items -> println("apple is fine too")
    }

    println()

    // 使用 lambda 表达式过滤和包装集合
    items.filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.toUpperCase() }
        .forEach { println(it) }
}


// 定义类
// 定义抽象类
abstract class Shape(val sides: List) {
    val perimeter: Double get() = sides.sum()
    abstract fun calculateArea(): Double
}

// 定义接口
interface RectangleProperties {
    val isSquare: Boolean
}

// 定义类 Rectangle 继承 Shape 并实现 RectangleProperties
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
}

// 定义类 Triangle 继承 Shape
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))
    }
}

更多文字内容参见官网

你可能感兴趣的:(在代码中学习 Kotlin 基本语法)