Kotlinlearncs.online LogoJava

    ← Prev

    Index

    Next →

    Kotlin
    Java
    • Data Modeling 1 : 29

    • Companion Objects : 28

    • Encapsulation : 27

    • Constructors : 26

    • Objects, Continued : 25

    • Introduction to Objects : 24

    • Compilation and Immutability : 23

    • Practice with Collections : 22

    • Maps and Sets : 21

    • Lists and Type Parameters : 20

    • Imports and Libraries : 19

    • Multidimensional Arrays : 18

    • Practice with Strings : 17

    • null : 16

    • Algorithms and Strings : 15

    • Strings : 14

    • Functions and Algorithms : 13

    • Practice with Functions : 12

    • More About Functions : 11

    • Errors and Debugging : 10

    • Functions : 9

    • Practice with Loops and Algorithms : 8

    • Algorithms I : 7

    • Loops : 6

    • Arrays : 5

    • Compound Conditionals : 4

    • Conditional Expressions and Statements : 3

    • Operations on Variables : 2

    • Variables and Types : 1

    • Hello, world! : 0

    Companion Objects

    Welcome back! Let’s continue deepening our understanding of Kotlin objects by describing a feature called companion objects. We’ll also introduce introduce one new piece of object syntax.

    Warm Up Debugging Challenge
    Warm Up Debugging Challenge

    But first, let’s warm up with another debugging challenge!

    this
    this

    this is a keyword in Kotlin that you can use in your instance methods. It always refers to the current instance that is executing the method.

    So this:

    class Course(var number: String) {
    fun changeNumber(newNumber: String) {
    number = newNumber
    }
    }

    is equivalent to this:

    class Course(var number: String) {
    fun changeNumber(newNumber: String) {
    this.number = newNumber
    }
    }

    The example above is one use of this. However, we’ll usually just go the first route, and choose parameter names that don’t conflict with our instance variable names. This helps avoid mistakes.

    However, there is one place where we do and will use this. Let’s go through it together:

    class Course(var number: String)

    Companion Objects
    Companion Objects

    Up until now the properties and methods that we’ve been establishing on our Kotlin objects are instance properties and methods. Meaning each instance of an class has its own:

    class Person(val name: String) {
    fun doubleName(): String {
    return name + name
    }
    }
    val first = Person("Geoff")
    val second = Person("Chuchu")
    println(first.name)
    println(second.name)
    println(first.doubleName())

    Even though they share an implementation of doubleName, instances each act like they have their own doubleName method.

    However, Kotlin also allows us to create methods that are provided by the class and can be accessed without an instance. We do this using something called a companion object. Let’s see how:

    class Person(val name: String)

    Companion v. Instance
    Companion v. Instance

    Companion object methods cannot access instance variables. Let’s look at why, and the differences between class and instance methods:

    class Person(val name: String) {
    companion object {
    fun getName(): String {
    return name
    }
    }
    }
    val student = Person("You")
    println(student.getName())

    Uses for Companion Objects
    Uses for Companion Objects

    In Kotlin, we can create methods that are not associated with any class, simply by declaring them outside a class body:

    class Person(val name: String)
    fun greetPerson(person: Person) {
    println("Hello ${person.name}!")
    }
    val geoff = Person("Geoff")
    greetPerson(geoff)

    This works completely fine, and limits the degree to which we need to use companion objects. So if you have a method that doesn’t need an instance, you can either declare it outside the class or in a companion object.

    Solve: Static Adder (Practice)

    Created By: Geoffrey Challen
    / Version: 2020.9.0

    Create a class named Math. Math should declare a companion object with a method named add. add should accept two Int arguments and return their sum.

    Companion Fields
    Companion Fields

    Companion objects can also declare fields, just like instances:

    class Person(val name: String) {
    companion object {
    val typicalGreeting = "Hello"
    }
    }
    println(Person.typicalGreeting)

    This can be a good place to put constant values, as shown above, particularly if, like a method, they really belong with the class that defines the companion object.

    You can also define non-constant (i.e., var) properties on companion objects. However. This is extremely rare, and very easy to get wrong. So much so that we won’t bother demonstrating how to do it!

    Solve: Toggler Object

    Created By: Geoffrey Challen
    / Version: 2021.9.0

    Define a class named Toggler with a single instance method named toggle that takes no parameters and returns a Boolean. Toggler should also provide a primary constructor that accepts a Boolean argument and sets the initial state of the Toggler instance.

    Toggler maintains one piece of private state: the Boolean. Calling toggle changes the Boolean from true to false or false to true and returns the new (not the old) state of the Boolean. So, for example:

    Note that the internal state should be private.

    More Practice

    Need more practice? Head over to the practice page.