Add Kotlin data mapping examples (BAEL-2247) (#5560)
This commit is contained in:
@@ -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
|
||||
)
|
||||
Reference in New Issue
Block a user