Home > Back-end >  Kotlin class operation on its KProperties
Kotlin class operation on its KProperties

Time:03-11

I have a big Kotlin object and need to do some operations on specific properties. Here is a small example for demo:

class ObjectForAnalysis {
  var id: Int = 0
  lateinit var successful: SUCCESSFUL
  var job1: Job? = null
  var job2: Job? = null
  var job3: Job? = null
}

Imagine that I have multiple instances of the object above and that I need to do the following operation on the properties of type Job.

job !=null && job.computeSquare() < 1000

How could I achieve that ?

CodePudding user response:

import kotlin.reflect.full.memberProperties

class Job(private var i: Int) {
  fun getI(): Int = i
}

class ObjectForAnalysis {
  var id: Int = 0
  var job1: Job? = null
  var job2: Job? = null
  var job3: Job? = null
}

val list = listOf(
  ObjectForAnalysis().also { it.id = 1; it.job1 = Job(2) },
  ObjectForAnalysis().also { it.id = 2; it.job1 = Job(4); it.job2 = Job(3); it.job3 = Job(9) },
  ObjectForAnalysis().also { it.id = 3; it.job1 = Job(12); it.job2 = Job(15) },
  ObjectForAnalysis().also { it.id = 4 },
)

val properties = ObjectForAnalysis::class.memberProperties.filter { it.name.startsWith("job") }

val result = list
  .filter { ofa ->
    properties
      .map { kProperty1 ->
        (kProperty1.get(ofa) as Job?)?.let { job: Job -> job.getI() < 10 }
      }
      .all { it != null && it == true }   // all i need to be < 10
      // .any { it != null && it == true }   // at least one i needs to be < 10
  }

println("result:")
result.forEach {
  println("id: ${it.id}, ints: ${it.job1?.getI()}, ${it.job2?.getI()}, ${it.job3?.getI()}")
}

println("excluded:")
list.minus(result).forEach {
  println("id: ${it.id}, ints: ${it.job1?.getI()}, ${it.job2?.getI()}, ${it.job3?.getI()}")
}

Output for .all { it != null && it == true }:

result:
id: 2, ints: 4, 3, 9

excluded:
id: 1, ints: 2, null, null
id: 3, ints: 12, 15, null
id: 4, ints: null, null, null

Output for .any { it != null && it == true }:

result:
id: 1, ints: 2, null, null
id: 2, ints: 4, 3, 9

excluded:
id: 3, ints: 12, 15, null
id: 4, ints: null, null, null
  • Related