Exercise: Converting and Creating a Measurement Unit
Enhance your Kotlin expertise by implementing extension functions for conversion between two classes and handling transformations of various data fields.
We'll cover the following
Problem statement
Implement two kinds of extension functions to facilitate smooth transformation between the User
and UserJson
classes. The User
class represents our domain object, while UserJson
represents the structure that is sent to the client.
Instructions
In the starting code, you’re provided with the basic structure of the User
, Email
, Centimeters
, and UserJson
classes. Your task is to implement the extension functions toJson()
and toUser()
, ensuring the specified conversion behavior:
Copy
username
as it is.Convert
email
to/fromString
using theEmail
class.Transform
registrationDate
to/fromString
in utilizingISO format ISO format refers to the international standard date and time notation (ISO 8601), representing dates and times in a specific format, such as 2022-02-15T12:30:45. parse
andtoString
fromLocalDateTime
.Convert
height
to/fromInt
through theCentimeters
class.Additionally, implement the
cm
extension property forInt
to create a correspondingCentimeters
object.Convert the
User
object to aUserJson
object.Convert the
UserJson
object back to aUser
object.
The actual output when running the provided code should be as follows:
Get hands-on with 1400+ tech skills courses.