kotlin随笔01

66 阅读1分钟
1. kotlin没有new()
val recordRepository = RecordRepository()

kotlin没有使用new关键字创建对象的实例,这是与Java的一个主要区别。

  • 2024.08.20
2. kotlin中没有switch
when (menuItem.itemId) {
    // 主页
    R.id.menu_monitor -> {
        handleFragmentSwitch(0)
    }
    // 监测记录
    R.id.menu_record -> {
        handleFragmentSwitch(1)
    }
    // 设置
    R.id.menu_setting -> {
        handleFragmentSwitch(2)
    }
}

kotlin中确实是没有switch语句,但是采用了更为强大和灵活的when语句

  • 2024.08.20
3. kotlin中集合的add

kotlin中,List接口本身并不提供add方法,因为它是一个可读的集合
add方法是MutableList接口的一部分,它是List接口的子接口,提供了修改列表的能力

// 错误
val familyInfoList: List<FamilyInfo> = mutableListOf()

// 正确
val familyInfoList: MutableList<FamilyInfo> = mutableListOf()