Primary Constructors
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 3 of 57.
Most Kotlin classes take their starting values in a primary constructor, written in parentheses after the class name. val or var in front of a parameter makes it a property at the same time:
class Book(val title: String, var pages: Int)Inside main:
val book = Book("Dune", 412)
println(book.title)
book.pages += 8
println(book.pages)Output:
Dune
420A parameter without val or var is only available while the instance is being created, for example to compute a property. val properties cannot be reassigned after creation; var properties can:
class Temperature(celsius: Double) {
val fahrenheit = celsius * 9 / 5 + 32
}Inside main:
val t = Temperature(100.0)
println(t.fahrenheit)Output:
212.0Constructor parameters can have default values and can be passed by name, so one constructor covers many ways of creating an instance:
class Timer(val seconds: Int, val label: String = "timer")Inside main:
val egg = Timer(300, "egg")
val quick = Timer(30)
val named = Timer(label = "tea", seconds = 180)
println("${egg.label} ${egg.seconds}")
println("${quick.label} ${quick.seconds}")
println("${named.label} ${named.seconds}")Output:
egg 300
timer 30
tea 180Inside the class body, this refers to the current instance. It is needed when a method parameter has the same name as a property:
class Player(var name: String) {
fun rename(name: String) {
this.name = name
}
}Inside main:
val p = Player("anon")
p.rename("Ada")
println(p.name)Output:
AdaChallenge
EasyDeclare the class Account with a primary constructor: a read-only owner and a changeable balance that defaults to 0. Add summary(), which returns Ada has 150.
The supplied code reads an owner and, when a second line is present, a starting balance. It creates the account with or without the balance and prints summary().
Your code goes in Account.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val account = if (input.size > 1) Account(input[0], input[1].toInt()) else Account(input[0])
println(account.summary())
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Kotlin playground