Kotlin: Classes

MJ Manaog
1 min readJan 2, 2021

--

Classes can be declared in Kotlin using the word class followed by its name and body inside curly braces.

class Moominvalley{
//class body
}

A class can have one or more Constructors, it can be declared as a Primary or a Secondary Constructor.

Primary Constructor Declaration

The primary constructor is part of the class header.

class Moominvalley(resident: String){//class body}

Secondary Constructor Declaration

class Moominvalley{

constructor(resident: String, kind: String){
print("Resident Name: $resident Kind: $kind")
}
}

Initializer Block

init{} will be always initialized

fun main() {
Moominvalley("Moominmama","Moomin")
}
class Moominvalley(resident: String){

constructor(resident: String, kind: String ): this(resident){
println("Resident Name: $resident Kind: $kind")
}
//initializer Block
init {
println("Welcome to Moominvalley, $resident!")
}
}
--------------
Output:
Welcome to Moominvalley, Moominmama!
Resident Name: Moominmama Kind: Moomin

Note: You can’t use the kind variable inside the initializer block because it is not accessible.

I’m still learning, please leave a comment if there’s something I need to improve/learn/ elaborate on. Arigato!

classy classes

--

--

MJ Manaog
MJ Manaog

No responses yet