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 }
相关推荐
码小猿的CPP工坊25 分钟前
C++跨平台开发之基于wxWidgets开发GUI程序简介-002
开发语言·c++
波力海苔夹心脆67527 分钟前
C# 固高 GTS 运动控制卡入门:伺服上下电、Jog 点动与二维插补(WinForms 实战)
服务器·开发语言·c#·运动控制·伺服电机·winforms·固高
海绵宝宝转agent34 分钟前
LeetCode100个人题解+java面经总结
java·开发语言·笔记·学习·算法
chenbingjie_c36 分钟前
C++ 继承全解析(从三种继承方式到菱形继承与内存布局)
开发语言·c++
学逆向的9 小时前
C 堆区内存管理
c语言·开发语言·网络安全
huoyueyi9 小时前
《融天AI-APP从0到1开发实录》
开发语言·lua
海水冷却9 小时前
Android 群组聊天怎么实现:基于 ZIM 的完整落地指南(附可运行 Demo)
android
OpenAnolis小助手11 小时前
PHP 两个严重漏洞曝光,龙蜥社区 24 小时完成 3 版本修复
开发语言·操作系统·php·龙蜥社区
阿尼卡~11 小时前
VS Code 配置 C 语言开发环境(Windows 10/11):从 GCC 安装到运行、断点调试,一篇搞定
c语言·开发语言·windows