Kotlin基础(①)

open 关键字:打破 Kotlin 的"默认封闭"规则

Kotlin 复制代码
// 基类必须加 open 才能被继承
open class Animal {
    // 方法也要加 open 才能被子类重写
    open fun makeSound() {
        println("Some sound")
    }
}

class Dog : Animal() {
    override fun makeSound() {
        println("Woof!")
    }
}

// 使用
val dog = Dog()
dog.makeSound() // 输出: Woof!

Lambda 表达式:简化匿名函数

Kotlin 复制代码
val numbers = listOf(1, 2, 3)

// ✅ 正确:单数参数名(代表每个元素)
numbers.filter { number -> number > 1 }

// ❌ 错误:复数参数名(容易误解为整个集合)
numbers.filter { numbers -> numbers > 1 } // 编译错误!因为 `numbers` 是单个元素,不能和数字比较
Kotlin 复制代码
data class Student(val name: String, val score: Int)

val students = listOf(
    Student("小明", 90),
    Student("小红", 80)
)

// ✅ 正确:单数参数名,代表每个学生对象
students.filter { student -> student.score > 85 }

// ✅ 也可以用 `it` 简写
students.filter { it.score > 85 }
相关推荐
小李飞飞砖16 分钟前
Sophix、Tinker 和 Robust 三大主流 Android 热修复框架的详细对比
android
ydm_ymz1 小时前
C语言初阶4-数组
c语言·开发语言
presenttttt1 小时前
用Python和OpenCV从零搭建一个完整的双目视觉系统(六 最终篇)
开发语言·python·opencv·计算机视觉
逐花归海.1 小时前
『 C++ 入门到放弃 』- 多态
开发语言·c++·笔记·程序人生
感觉不怎么会2 小时前
Android 12 - 部分相机横屏显示方案
android
卜锦元2 小时前
Go中使用wire进行统一依赖注入管理
开发语言·后端·golang
军训猫猫头2 小时前
3.检查函数 if (!CheckStart()) return 的妙用 C#例子
开发语言·c#
coding随想2 小时前
JavaScript中的系统对话框:alert、confirm、prompt
开发语言·javascript·prompt
灵哎惹,凌沃敏2 小时前
C语言/Keil的register修饰符
c语言·开发语言