deepCopy

fun <T : Any> T.deepCopy(targetType: Class<T> = this.javaClass): T

Converts this object to an instance of the specified target type.

Uses Jackson's convertValue to perform type conversion, which maps properties between the source and target objects. The target type must have compatible property names and types for successful conversion.

This method is useful for:

  • Converting between data classes with similar structures

  • Creating copies with a different type

  • Transforming object representations

Receiver

The object to convert.

Return

A new instance of the target type with mapped properties.

Parameters

T

The type of the object being converted.

targetType

The Class representing the target type. Defaults to the object's class.

Throws

JsonProcessingException

if conversion fails.

Example:

data class User(val name: String, val age: Int)
data class UserDto(val name: String, val age: Int)
val user = User("John", 30)
val dto = user.deepCopy<UserDto>()