MST

星途 面试题库

面试题:Kotlin范围表达式与自定义对象比较

定义一个包含`age`属性的`Person`类,并重写其`compareTo`方法以基于`age`进行比较。然后,使用Kotlin的范围表达式创建一个从年龄为20到30(包含20和30)的`Person`对象范围。假设存在一个`List<Person>`,请编写代码从该列表中筛选出处于此年龄范围内的人员。
30.5万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
class Person(val age: Int) : Comparable<Person> {
    override fun compareTo(other: Person): Int {
        return this.age - other.age
    }
}

fun main() {
    val ageRange = 20..30
    val personList = listOf(
        Person(18),
        Person(22),
        Person(25),
        Person(35)
    )
    val filteredList = personList.filter { it.age in ageRange }
    println(filteredList.map { it.age })
}