Classes in Kotlin – Part 1

Why is there a car in the picture? – Because it has class!

Jokes aside, classes are still the building blocks of modern object oriented software design. And of course as the new kid on the block Kotlin has it’s own take on this subject.

Declaration

Let’s look at the most basic class declaration:

class Earth{
    
  val diameter = 12756
    
  val distanceToSun = 149.6e6
    
  val mass = 5.9724e24

}

 

Initialization

class Planet(
    
  val diameter: Int,
    
  val distanceToSun: Double,
    
  val mass: Double

)

Instantiation

fun main() {
    
  val earth = Planet(diameter = 12756, distanceToSun = 149.6e6, mass = 5.9724e24)
    
  println(earth.diameter)
    
  println(earth.distanceToSun)
    
  println(earth.mass)
}