Android Mastery: Defining Classes in Kotlin

Photo by rivage on Unsplash

Android Mastery: Defining Classes in Kotlin

Kotlin Developer Path Ep2

Bismillah

Defining classes in Kotlin involves specifying the properties and methods that all objects of that class should have.

Syntax

class [class_name] {
    /*[body: 
                contains properties and methods
    ]*/
}
  • Choose any class name except for Kotlin keywords.

  • Write the “ClassName” in “PascalCase”, where each word begins with a capital letter and no space between the words.

Parts Of A Class

  • Properties: These variables specify the attributes of the class’s objects.

  • Methods: These are functions within the class that contain the actions and behaviors of the class.

  • Constructors: This is a special member function used to create instances of the class throughout the program in which it’s defined.

Examples Of Classes In Kotlin

While studying the basics of Kotlin, we often get introduced to the following datatypes:

  • Int

  • Float

  • String

  • Double

Each of these datatypes is defined as a class in Kotlin, meaning that the following snippet of code creates an instance of the String class, instantiated with the value assigned to it:

val name: String = "Umar Ndungo"

Let’s now define our class that we can then create instances of:

class SoftwareEngineer {
        /* body */
}

Creating Instances Of A Class

As discussed in our previous article, the class is a blueprint of an object, at runtime Kotlin uses this blueprint to create an object(s) of that particular type.

With the class above, you have a blueprint of a "SoftwareEngineer".

To create the actual “SoftwareEngineer” you’ll need to create an object instance of the class.

To instantiate you’ll need the class name and a set of parentheses, as in:

SoftwareEngineer()

To use an object, you create the object as shown above and assign it to a variable either as a:

  • value → val: (for immutable objects) and,

  • variable → var: (for mutable objects).

fun main() {
        // PS: For compilation Kotlin 
        // needs the main() function to be present.
        // An object instance of the Software Engineer Class
        val umar_ndungo = SoftwareEngineer()
}

Defining Class Methods

A method, simply put, is a function within a class. As a refresher functions are defined as:

fun [functionName](): [returnType] {}

/* Return type is not compulsory, however it is recommended */

For our method(s) within the software engineer class, we define them as:

class SoftwareEngineer {
        ...
        fun gotAJob() {
                // we'll use this to update the employed variable
                employed = true

                println("Excited to start a new role!")
        }

        fun leftAJob(){
                // we'll use this to update the employed variable
                employed = false

                println("Sad to have lost the role!")
        }
}

Calling A Method On An Object

A class method can be called:

  • Within another method in the class.

      fun gotAJob(var quit: Boolean){
              // had to quit to go into the other job
              if (quit) {
                      lostAJob()
              }
    
              ...
      }
    
  • By an object outside of the class to perform a function, by referencing both the class and the method name.

      // className.methodName()
    
      fun main() {
              ...
    
              umar_ndungo.gotAJob(quit = false)
    
      }
    

Defining Class Properties

Similar to variables, the class properties will be created either as:

  • Value “val”: to create immutable properties, similar to constants in other languages.

  • Variable “var”: to create mutable properties, which are expected to change.

For example, a Software Engineer has the following properties:

  • Name: the name the software engineer goes by, legally or otherwise.

  • Employed: the software engineer’s job status.

  • Student: the software engineer's student status.

  • Experience: the number of years of experience the software engineer has.

Defining properties in a class is as follows:

class SoftwareEngineer {
        ...
        // here we assign default variables to be updated
        var name: String = ""
        var employed: Boolean = false
        var student: Boolean = false
        var experience: Double = 0.0

        ...
}

Getter And Setter Functions In Properties

PLEASE NOTE: Properties can do more than variables.

How?

  • With a property like “experience”, it is expected that as a "SoftwareEngineer" progresses in their career, they gain more years of experience on the job.

  • The minimum number of years is set as the default in this case.

  • The maximum number of years is not defined, as people retire from their Software Engineering careers at different times.

  • To ensure the experience does not go below 0, we need a setter function. Each time we update the experience value, a check to confirm that it is not below 0 is necessary.

Syntax

var [name]: [data type] = [initialvalue]
    get() {
        [body]    
    }
    set(value) {
        [body]
    }

PS: When you don’t define the getter and setter functions for a property, the Kotlin compiler creates them internally.

For example

var experience = 0
    get() = field // Kotlin compiler creates these internally
    set(value) { // they will not appear in the code
        field = value
    }

PS: An immutable property(val) does not contain a set() function.

TO NOTE

  • Backing Field(field): a class variable, used to hold a value in memory, that is defined and accessed only within the scope of a property’s get and set functions.

  • To read the property value in the get() function or update the value in the set() function, you’ll need the property’s backing field, which is autogenerated by the Kotlin compiler and referenced with a “field” variable.

      var experience = 0
          get() = field
          set(value) {
              field = value
          }
    

To ensure the level of experience of the Software Engineer never goes below 0:

var experience: Double = 0.0
    set(value) {
        if (value >= 0.0){
            field = value
        }
    }

Putting It All Together

With properties and methods in mind, here's our final draft, including how to assign variables and call functions.

class SoftwareEngineer {
        var name: String = ""
        var employed: Boolean = false
        var student: Boolean = false
        var experience: Double = 0.0

        fun gotAJob() {
                // we'll use this to update the employed variable
                employed = true

                println("Excited to start a new role!")
        }

        fun leftAJob(){
                // we'll use this to update the employed variable
                employed = false

                println("Sad to have lost the role!")
        }
}

fun main() {
    println("Hello, world!!!")

    val umarNdungo = SoftwareEngineer()
    umarNdungo.name = "Umar Ndungo"
    umarNdungo.employed = false
    umarNdungo.student = false
    umarNdungo.experience = 0.5

    umarNdungo.gotAJob()
    println(umarNdungo)
}

Well, there you have it, I'm still learning, and these are my notes from that, so let's see how far this goes In shaa Allah.

Asalaam Aleykum.