0
0
Kotlinprogramming~20 mins

Extension properties in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Extension Properties in Kotlin
📖 Scenario: Imagine you want to add a new way to get the full name of a person without changing the original Person class. Kotlin's extension properties let you do this easily.
🎯 Goal: Build a Kotlin program that uses an extension property to get the full name of a Person object by combining first and last names.
📋 What You'll Learn
Create a Person class with firstName and lastName properties
Create an extension property called fullName for the Person class
Use the fullName extension property to print the full name of a person
💡 Why This Matters
🌍 Real World
Extension properties let you add new features to existing classes, like adding a new way to get a full name, without changing the original code. This is useful when working with libraries or code you cannot modify.
💼 Career
Many Kotlin developers use extension properties to write cleaner and more readable code by extending functionality in a simple way. This skill is valuable for Android development and backend Kotlin projects.
Progress0 / 4 steps
1
Create the Person class
Create a Kotlin class called Person with two val properties: firstName and lastName, both of type String. Initialize them using the primary constructor.
Kotlin
Need a hint?

Use class Person(val firstName: String, val lastName: String) to define the class with properties.

2
Add an extension property for fullName
Create an extension property called fullName for the Person class that returns a String. It should combine firstName and lastName separated by a space.
Kotlin
Need a hint?

Use val Person.fullName: String get() = "$firstName $lastName" to create the extension property.

3
Create a Person object and use fullName
Create a variable called person of type Person with firstName set to "John" and lastName set to "Doe". Then create a variable called name and assign it the value of person.fullName.
Kotlin
Need a hint?

Create person with Person("John", "Doe") and assign person.fullName to name.

4
Print the full name
Write a println statement to print the value of the variable name.
Kotlin
Need a hint?

Use println(name) to display the full name.