w3resource

Kotlin Class: Create and print person details

Kotlin Class: Exercise-1 with Solution

Write a Kotlin program that creates a class 'Person' with properties for name, age, and country. Include a function to print the person's details.

Sample Solution:

Kotlin Code:

class Person(val name: String, val age: Int, val country: String) {
    fun printDetails() {
        println("Name: $name")
        println("Age: $age")
        println("Country: $country")
    }
}

fun main() {
    val person = Person("Dilara Cilla", 25, "Spain")
    person.printDetails()
}

Sample Output:

Name: Dilara Cilla
Age: 25
Country: Spain

Explanation:

In the above exercise -

  • First we define a class Person with three properties: name, age, and country. The class also includes a function printDetails() that prints the person's details by accessing the property values.
  • In the main() function, we create an instance of the Person class with the name "Dilara Cilla", age 25, and country "Spain". We then call the printDetails() function on the 'person' object to print the details.

Kotlin Editor:


Previous: Kotlin Class Exercises Home.
Next: Create and calculate rectangle area.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/class/kotlin-class-exercise-1.php