Add Kotlin data mapping examples (BAEL-2247) (#5560)
This commit is contained in:
parent
bf2da7e686
commit
c10101a9ac
|
@ -40,3 +40,4 @@
|
|||
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
|
||||
- [Concatenate Strings in Kotlin](https://www.baeldung.com/kotlin-concatenate-strings)
|
||||
- [Kotlin return, break, continue Keywords](https://www.baeldung.com/kotlin-return-break-continue)
|
||||
- [Mapping of Data Objects in Kotlin](https://www.baeldung.com/kotlin-data-objects-mapping)
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.datamapping
|
||||
|
||||
data class User(
|
||||
val firstName: String,
|
||||
val lastName: String,
|
||||
val street: String,
|
||||
val houseNumber: String,
|
||||
val phone: String,
|
||||
val age: Int,
|
||||
val password: String)
|
|
@ -0,0 +1,22 @@
|
|||
package com.baeldung.datamapping
|
||||
|
||||
import kotlin.reflect.full.memberProperties
|
||||
|
||||
fun User.toUserView() = UserView(
|
||||
name = "$firstName $lastName",
|
||||
address = "$street $houseNumber",
|
||||
telephone = phone,
|
||||
age = age
|
||||
)
|
||||
|
||||
fun User.toUserViewReflection() = with(::UserView) {
|
||||
val propertiesByName = User::class.memberProperties.associateBy { it.name }
|
||||
callBy(parameters.associate { parameter ->
|
||||
parameter to when (parameter.name) {
|
||||
UserView::name.name -> "$firstName $lastName"
|
||||
UserView::address.name -> "$street $houseNumber"
|
||||
UserView::telephone.name -> phone
|
||||
else -> propertiesByName[parameter.name]?.get(this@toUserViewReflection)
|
||||
}
|
||||
})
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
package com.baeldung.datamapping
|
||||
|
||||
data class UserView(
|
||||
val name: String,
|
||||
val address: String,
|
||||
val telephone: String,
|
||||
val age: Int
|
||||
)
|
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.datamapping
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import org.junit.jupiter.api.assertAll
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class UserTest {
|
||||
|
||||
@Test
|
||||
fun `maps User to UserResponse using extension function`() {
|
||||
val p = buildUser()
|
||||
val view = p.toUserView()
|
||||
assertUserView(view)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `maps User to UserResponse using reflection`() {
|
||||
val p = buildUser()
|
||||
val view = p.toUserViewReflection()
|
||||
assertUserView(view)
|
||||
}
|
||||
|
||||
private fun buildUser(): User {
|
||||
return User(
|
||||
"Java",
|
||||
"Duke",
|
||||
"Javastreet",
|
||||
"42",
|
||||
"1234567",
|
||||
30,
|
||||
"s3cr37"
|
||||
)
|
||||
}
|
||||
|
||||
private fun assertUserView(pr: UserView) {
|
||||
assertAll(
|
||||
{ assertEquals("Java Duke", pr.name) },
|
||||
{ assertEquals("Javastreet 42", pr.address) },
|
||||
{ assertEquals("1234567", pr.telephone) },
|
||||
{ assertEquals(30, pr.age) }
|
||||
)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue