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 }
相关推荐
2601_962885724 小时前
如何用 Python 自动识别股票的支撑位与压力位?
开发语言·python
爱吃奥利奥_wen4 小时前
面向对象三板斧:封装、继承、多态,到底在“装“什么、“承“什么、“变“什么?
开发语言·经验分享·c#
我可能是个假开发4 小时前
FTP Unicode 文件名导致 `550` 的问题分析与解决方案
java·开发语言·spring
WL学习笔记6 小时前
日期类(C++)
开发语言·c++·日期类实现
Android系统攻城狮6 小时前
Linux Gstreamer深度解析之gst_audio_encoder_set_frame_max调用流程与实战(六十一)
android·linux·运维·音视频·gstreamer音视频·音视频进阶·gstreamer音视频进阶
谢亮_vipxieliang6 小时前
Go map与结构体的正确使用
开发语言·golang·哈希算法
H.莓飛7 小时前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
xxwl5857 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
传奇开心果编程9 小时前
【Compose Multiplatform 跨端开发学与练】第7课 平台适配与互操作
android·windows·学习·ui·ios·kotlin·composer
mmsx9 小时前
Android 地图数据链路:从 GDAL、KML 到多引擎适配
android·kotlin