Kotlin and Copilot: create a person class with a name
Video: Kotlin and Copilot: create a person class with a name by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin and Copilot: Create a Person Class with a Name
In Kotlin, defining a simple class with a constructor parameter and a method is straightforward. This example demonstrates how to create a Person class that takes a name as a parameter and includes a method to print that name.
Code
class Person(val name: String) {
// Method to print the person's name
fun printName() {
println("Name: $name")
}
}
fun main() {
val person = Person("Alice")
person.printName() // Output: Name: Alice
}
Key Points
- Kotlin classes can have primary constructors defined directly in the class header.
- Using
valin the constructor parameter makes the property immutable and accessible. - Class methods like
printNamecan access properties defined in the constructor. - Creating an instance of the class and calling its method demonstrates basic object-oriented usage.