What a class is
A class is a blueprint. It describes what data an object holds and what the object can do. An object (also called an instance) is one concrete thing built from that blueprint, with real values. Employee can be a class, while an employee named Andrew who is 30 years old is an object. One class can produce many objects, each with its own values.
A class is declared with the class keyword:
class Employee {
}
Creating objects
Kotlin creates an object by calling the class name like a function. There is no new keyword:
val employee = Employee()
The variable is a val, so it always refers to the same object. That doesn't stop the object's own var properties from changing.
Properties
Variables that belong to an object are called properties. Each object gets its own copy. Declare them inside the class body with var (can be reassigned) or val (cannot), and give them an initial value:
class Employee {
var name: String = ""
var age: Int = 0
}
fun main() {
val emp1 = Employee()
emp1.name = "Andrew"
println(emp1.name) // Andrew
val emp2 = Employee()
emp2.age = 40
println(emp2.age) // 40
}
The dot operator reads or writes a property: emp1.name. Changing emp1 doesn't affect emp2, since each has separate storage. Properties and members are public by default in Kotlin, so no keyword is needed for code outside the class to use them. Marking a member private hides it: reading a private count from outside the class is a compile error.
Constructors
Usually you want to set the values while creating the object. A constructor does that. Kotlin's most common form is the primary constructor, written in the class header:
class Person(val name: String, var age: Int) {
fun describe() {
println("$name is $age")
}
}
fun main() {
val p = Person("Mary", 25)
p.describe() // Mary is 25
}
Writing val or var before a parameter in that header declares a property and sets it from the argument in one step. Without it, the parameter exists only for initialization and can't be used inside methods. This is the form the lesson's exercise uses.
A class can also declare a secondary constructor with the constructor keyword, which is useful when you want several ways to create objects. In that form the properties are declared in the body and assigned with this:
class Employee {
var name: String = ""
var age: Int = 0
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
Inside a class, this refers to the object being worked on. Here this.name is the property, and plain name is the parameter that shadows it. Without a name clash, this. is optional. The primary constructor form is shorter and is the one to prefer.
Methods
Functions declared inside a class are called methods (or member functions). They are called with the dot syntax on an object and can use that object's properties directly:
class Person(val name: String, var age: Int) {
fun birthday() {
age += 1
}
fun describe() {
println("$name is $age")
}
}
fun main() {
val p = Person("Mary", 25)
p.birthday()
p.describe() // Mary is 26
}
A method without a declared return type returns Unit, Kotlin's counterpart of void.
The exercise, step by step
The lesson asks for a class Job with a title and a method that announces the job, then uses it inside mainFunction.
- Declare
class JobaboveSolution, withvar title: Stringin the primary constructor. Declaring and storing the title takes one line. - Add a method
hireMeinsideJob, withfunand no parameters. - Print the message in the method:
"You're hired as a "followed bytitle, joined with+. The property is available directly, withoutthis. - Create the object in
mainFunction:val job = Job("Software Engineer"). - Call the method with
job.hireMe(). Creating the object prints nothing by itself; the message appears when the method runs.
class Job(var title: String) {
fun hireMe() {
println("You're hired as a " + title)
}
}
class Solution {
fun mainFunction() {
val job = Job("Software Engineer")
job.hireMe()
}
}
When mainFunction runs, it prints You're hired as a Software Engineer. A string template, "You're hired as a $title", would give the same text, and it is the more common style.
Common mistakes
- Leaving out
valorvarin the constructor header.class Job(title: String)compiles, buttitleis then only a constructor parameter. Using it insidehireMefails with an unresolved reference. - Using
new. Kotlin has no such keyword. WriteJob("..."). - Reassigning a
valproperty. Iftitlewere declared withval, thenjob.title = "Manager"would not compile. Usevarfor properties that change. - Forgetting the parentheses on a call.
job.hireMewithout()doesn't run the method. - Comparing objects with
==. For an ordinary class,==istrueonly for the same object, so twoPerson("a", 1)objects are not equal. Kotlin'sdata classchanges that.
Key takeaways
- A class defines the properties and methods; objects are created by calling the class name.
- Put
valorvarbefore a primary-constructor parameter to make it a property. - Members are public by default, and
privatehides them. - Methods are called with the dot, and they use the object's own properties.