Ronnie Atuhaire's Blog 😎

Ronnie Atuhaire's Blog 😎

Kotlin Classes

Kotlin Classes

Subscribe to my newsletter and never miss my upcoming articles

Hello there👋, welcome back to my blog! Today, we shall be learning more bout classes in Kotlin. If you have missed any classes in the series, kindly check them out here.

✨ What Are Classes❓

image.png In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behaviour (member functions or methods). By Wikipedia

Basically, a class is a blueprint that defines the variables and the methods common to all objects of a certain kind.

Python is an O-O-P language whereas Kotlin has both object-oriented and functional constructs. You can use it in both OO and FP styles, or mix elements of the two.

Kotlin’s object model is substantially different from Python’s. Most importantly, classes are not dynamically modifiable at runtime!

🔹 Declaration and Instantiation

Just like Python, Kotlin Classes are also declared with the class keyword. A basic class without any properties or functions of its own looks like this:

class className{   // class header  
      // property  
      // member function  

It's conventional for class names to use UpperCamelCase, just like in Python.

🔹 Object Creation

You can then create an instance of this class in a way that looks similar to Python as if the class were a function (but this is just syntactic sugar - unlike Python, classes in Kotlin aren’t really functions):

val object = className()

🔹 Properties

Let’s make a class with some properties:

class Person {
    var name = "Anne"
    var age = 32

Note that the type of property must be explicitly specified. As opposed to Python, declaring a property directly inside the class does not create a class-level property, but an instance-level one: every instance of Person will have its own name and age.

Their values will start out in every instance as "Anne" and 32, respectively, but the value in each instance can be modified independently of the others:

val a = Person()
val b = Person()

Let's make an output of these:

println("${a.age} ${b.age}") // Prints "32 32"
a.age = 42
println("${a.age} ${b.age}") // Prints "42 32"

To be fair, you’d get the same output in Python, but the mechanism would be different: both instances would start out without any attributes of their own (age and name would be attributes on the class), and the first printing would access the class attribute; only the assignment would cause an age attribute to appear on a.

In Kotlin, there are no class properties in this example, and each instance starts out with both properties. If you need a class-level property, see the section on companion objects.

Property names should use lowerCamelCase instead of snake_case.

🔹 Member functions

A function declared inside a class is called a member function of that class.

Like in Python, every invocation of a member function must be performed on an instance of the class, and the instance will be available during the execution of the function - but unlike Python, the function signature doesn’t declare that: there is no explicit self parameter.

image.png Instead, every member function can use the keyword this to reference the current instance, without declaring it. Unlike Python, as long as there is no name conflict with an identically-named parameter or local variable, this can be omitted. If we do this inside a Person class with a name property:

Example: Let's assume this resides in our Person() class above.

fun present() {
    println("Hello, I'm $name!")

We can then do this:

val p = Person("Claire")
p.present() // Prints "Hello, I'm Claire!"

You could have said ${}, but that’s redundant and generally discouraged. Oneliner functions can be declared with an =:

fun greet(other: Person) = println("Hello, ${}, I'm $name!")

Apart from the automatic passing of the instance into this, member functions generally act like ordinary functions.

Because the set of member functions of an object is constrained to be exactly the set of member functions that are declared at compile-time in the object’s class and base classes, it’s not possible to add new member functions to an object or to a class at runtime, so e.g. p.leave = fun() { println("Bye!") } or anything of the sort won’t compile.

Member function names should use lowerCamelCase instead of snake_case.

🔹 Constructors and initializer blocks

Properties that don’t have a sensible default should be taken as constructor parameters. Like with Python’s __init__(), Kotlin constructors and initializer blocks run automatically whenever an instance of an object is created (note that there’s nothing that corresponds to __new__()).

A Kotlin class may have one primary constructor, whose parameters are supplied after the class name.

The primary constructor parameters are available when you initialize properties in the class body, and also in the optional initializer block, which can contain complex initialization logic (a property can be declared without an initial value, in which case it must be initialized in init).

Also, you’ll frequently want to use val instead of var in order to make your properties immutable after construction.

class Person(firstName: String, lastName: String, yearOfBirth: Int) {
    val fullName = "$firstName $lastName"
    var age: Int

    init {
        age = 2018 - yearOfBirth

If all you want to do with a constructor parameter value is to assign it to a property with the same name, you can declare the property in the primary constructor parameter list (the oneliner below is sufficient for both declaring the properties, declaring the constructor parameters, and initializing the properties with the parameters):

class Person(val name: String, var age: Int)

✨ Conclusion

We have learned how to declare classes, create instance objects, member functions and class constructors as the main basics of classes in Kotlin.

This Github Page by Khan was of great help!

We shall stop here for today and we shall learn more about other related classes functionality and types of classes that we can have in Kotlin.

If you enjoyed this, follow me on Twitter& here!

Ronnie Atuhaire 😎

Share this