Home > OS >  How to map an instance match in kotlin
How to map an instance match in kotlin

Time:08-20

I have List<Any> which have different data class inside of it, and I have this scenario that one of that data class some parameter will transform.

example:

private fun List<Documents>.documentList() = listOf<Any>(
 DataClassItemDto1(
  uniqueParameters = "blabla"
 ),
 DataClassItemDto2(
  uniqueParameters = "blabla"
 ),
 DataClassItemDto3(
  uniqueParameters = "blabla"
 ),
)

then:

 documentsResponse
  .findAll { it.typeOfDocuments == "DONE" }
  .documenList()
  // which I know the return here will be the filtered I just want to update some value from the data class instance
  .filterIsIntance<DataClassItemDto2>() 
  .map { it.copy(uniqueParameters = newValue) }

maybe do we have here a mapIsIntance also??

CodePudding user response:

There's no special way to do it. Just do it the same way you would for a non-collection.

.map { if (it is DataClassItemDto2) it.copy(uniqueParameters = newValue) else it }

CodePudding user response:

so my conclusion for this one is to create a generic iterable function which is this

/**
 * Unlike [filterIsInstance] which will return only the filter of the instance
 * if we want to transform only the instance from the list given then
 * this function will map only the instance of T from the iterable elements.
 * */
fun <T> Iterable<*>.mapInstanceOf(kclass: Class<T>, transform: T.() -> T) =
    map { objectItem -> if (kclass.isInstance(objectItem)) transform else objectItem }

so then I can do this way:

documentsResponse
  .findAll { it.typeOfDocuments == "DONE" }
  .documenList() 
  .mapInstanceOf(DataClassItemDto2::class.java) { copy(uniqueParameters = newValue) }

I did a unit test for this and all pass.

  • Related