请让我怎样打印出人员内容?
代码的输出是
[Person@72ea2f77, Person@33c7353a, Person@681a9515, Person@3af49f1c,
Person@19469ea2]
代码:
fun main(args: Array<String>) {
val person1 = Person("xyz1", 10);
val person2 = Person("xyz2", 20);
val person3 = Person("xyz3", 30);
val person4 = Person("xyz4", 40);
val person5 = Person("xyz5", 50);
var persons = listOf(
person1, person2, person3, person4 , person5)
.asSequence()
.filter { x-> x.age >=30 }
println(persons.toList())
}
答案 0 :(得分:2)
您可以在toString()
类中实现Person
方法,也可以使Person
类成为data class
。
答案 1 :(得分:0)
显示Person类内容的一种简单方法是覆盖Persons类中的toString方法。这是一个工作示例:
fun main(args: Array<String>) {
val person1 = Person("xyz1", 10);
val person2 = Person("xyz2", 20);
val person3 = Person("xyz3", 30);
val person4 = Person("xyz4", 40);
val person5 = Person("xyz5", 50);
var persons = listOf(
person1, person2, person3, person4, person5)
.asSequence()
.filter { x -> x.age >= 30 }
println(persons.toList())
}
class Person constructor(val name: String, val age: Int) {
override fun toString(): String {
return "$name is $age years old."
}
}
将输出:
[xyz3是30岁。xyz4是40岁。xyz5是50岁。]