Issue
I have a class that has the following format:
class Student(var name: String) {
var name: String? = null
var Math: Course? = null
var English: Course? = null
var Spanish: Course? = null
}
class Course {
var id: Int
var courseGrade: Int? = null
}
And I have a variable that is of type Student
var studentData = Student("test")
I need to iterate through all courses and get the grade of the highest course that's in class Student, to assign it to a "highestScore" variable. How can I iterate through the properties that have values in other class types?
Solution
The Student
class is not designed properly for such a feature (you would need reflection to do what you want, which is really not advised here).
If you need to consider courses as a collection of things (to be able to iterate on them or perform operations on them), you should represent it as such in your class. For instance, you can use List<Course>
:
class Student(
val name: String? = null,
val courses: List<Course> = emptyList(),
)
class Course(
val id: Int,
val name: String,
val courseGrade: Int? = null
)
Then you can easily get the information you need:
val maxGrade = studentData.courses
.filter { it.courseGrade != null }
.maxOfOrNull { it.courseGrade!! }
But probably it would be better to not have a nullable grade here. Is it expected to have some course instances without a grade? If not, making it non-nullable makes the code even simpler:
val maxGrade = studentData.courses.maxOfOrNull { it.courseGrade }
If you really have to stick with this class structure, then I see mainly 2 solutions to get the list of courses (and then apply the above):
- list properties by hand
- find properties via reflection
For #1:
val courses = listOfNotNull(student.Math, student.English, student.Spanish)
Or to make it less verbose if you have many courses properties:
val courses = with(student) { listOfNotNull(Math, English, Spanish) }
For #2 (requires kotlin-reflect
and honestly I really don't advise this):
private fun KProperty1<Student, *>.isNullableCourseType() = returnType.isSubtypeOf(Course::class.createType(nullable = true))
And then:
val courses = Student::class.memberProperties
.filter { it.isNullableCourseType() }
.mapNotNull { it.get(studentData) }
Answered By - Joffrey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.