Understand classes in Kotlin

In computer programming, we use classes to define templates for how to describe things. A class can represent a thing: A person, a chair, a bank account, a musical instrument, and so on. Each thing, or object, can have properties. For instance, a musical instrument can belong to a certain family: strings, woodwinds, brass, percussion, or voice. It can have a range, from lowest note to highest. It can have subcategories (or child classes): A string instrument has a certain number of strings, and might be bowed or plucked. A woodwind instrument can have 0, 1, or 2 reeds. A percussion instrument can have definite pitch (like a marimba or tympani) or indefinite pitch (like cymbals or a snare drum).

This essay introduces how to work with classes in Kotlin. This article assumes you know the basics of the Kotlin language and how to run Kotlin code. If you’d like to follow along with these code examples, all of this can be run in the Kotlin Playground or your favorite Kotlin IDE.

Create a new class

To create a class in Kotlin, you use the class keyword, followed by the name of your choice in TitleCamelCase:

class MusicalInstrument

A class can have constructor parameters. Constructor parameters are added in parentheses after the class name. I like to start each parameter name with an underscore, to differentiate between them and any properties defined later in the class. (More on that later…)

class MusicalInstrument(_name: String, _family: String, _height: Double, _width: Double, _clef: String)

You can make your parameters easier to read by putting them on different lines. Here I line them up vertically, but you can format them a number of ways and still have valid code. Just remember to make it all readable and consistent:

class MusicalInstrument(
    _name: String,
    _family: String,
    _height: Double,
    _width: Double,
    _length: Double,
    _clef: String)

Class properties

A class has properties inside the curly braces section. You can immediately initialize your properties with parameters:

class MusicalInstrument(
    _name: String,
    _family: String,
    _height: Double,
    _width: Double,
    _length: Double,
    _clef: String)
{
    val name = _name
    val family = _family
    val height = _height
    val width = _width
    val length = _length,
    val clef = _clef 
}

You can actually make the above code even simpler by declaring the properties right in the parameter declaration with val or var. This example eliminates the need for that underscore convention I mentioned earlier, and instead declares the parameters I need right up front:

class MusicalInstrument(
    val name: String,
    val family: String,
    val height: Double,
    val width: Double,
    val length: Double,
    val clef: String)
{

}

You can add additional parameters in the body of your class definition. Here’s an example of a volume parameter, which is calculated based on the dimensions of the instrument – useful when planning your next orchestra tour:

class MusicalInstrument(
    val name: String,
    val family: String,
    val height: Double,
    val width: Double,
    val length: Double,
    val clef: String)
{
    var volume = height * width * length
}

Create an instance of a class

Now that you have a fairly well-defined class, the next step is to create an instance of it and start calling it from your program. In this example, use the var keyword to create an instance of MusicalInstrument in main() called instrument.

fun main() {
  var violin = MusicalInstrument(
    "Violin", "strings",
    12, 25, 60,
    "treble")
}

class MusicalInstrument(
    val name: String,
    val family: String,
    val height: Double,
    val width: Double,
    val length: Double,
    val clef: String)
{
    var volume = height * width * length
}

This above code uses the MusicalInstrument class as a template to describe a violin. Now you can extract data from it and have it appear in your program:

fun main() {
  var violin = MusicalInstrument(
    "Violin", "strings",
    12, 25, 60,
    "treble")
  println("The ${violin.name} is in the ${violin.family} family")
}
...

You can access the defined parameters such as the name of the instrument and the instrument family because you added those parameters to the instance. You can also access the properties that were defined in the body of the class:

fun main() {
  var violin = MusicalInstrument(
    "Violin","strings",
    12, 25, 60,
     "treble")
  println("The ${violin.name} is in the ${violin.family} family")
  println("Volume: ${violin.volume} cm³")
}
...

In the above example, you called violin.volume from the MusicalInstrument class, and it took your inputs of height, width, and length and did the math for you!

You can also add functions to classes. When a function exists as part of a class, it is called a method. This example moves the println() work to the class and then calls it with violin.printInfo():

fun main() {
  var violin = MusicalInstrument(
    "Violin","strings",
    12, 25, 60,
     "treble")
  violin.printInfo()
}

class MusicalInstrument(
  val name: String,
  val family: String,
  val height: Int,
  val width: Int,
  val length: Int,
  val clef: String) {
  var volume = height * width * length
  fun printInfo() {
    println("Instrument: $name")
    println("Family: $family")
    println("Clef: $clef")
    println("Volume: $volume cm³")
  }
}

This is just a quick introduction to Kotlin classes. In future posts, I’ll explore polymorphism, inheritance, and more. Stay tuned…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: