Kotlin

To share this page click on the buttons below;

Classes

Classes are declared in the following way

class <class_name> {
   <class body>
}

Function members and data members have access modifier to define their scope:

  • private: accessed inside the class only
  • public: accessed everywhere
  • protected: accessed to the class and its subclasses
  • internal: accessed inside the module

Access modifier can be applied to whole class using the modifier before the word class.

Primary constructor

Class declaration with arguments defines primary constructor. The initialization code is embedded in the class body with init sections.

class <class_name>(<arguments>) {
   <class body 1>

   init {
      <initialization code 1>
   }

   <class body 2> 

   init {
      <initialization code 2>
   }
}

You can use as many init sections are needed and they are executed in the order they are written. Constructor arguments are available in the init sections and to initialize class properties.

Use val to make properties immutable after construction.

Class property can be embedded in the constructor argument list so that:

class <class name>(val <property_name>:type)

already defines the property .

Secondary constructor

Secondary constructor can be defined: they must have different argument list and must call always another constructor (both primary or secondary).

Secondary constructor are functions inside the class declaration named constructors, they call the primary constructor using this.

class <class_name>(<arguments>) {

  constructor(<arguments>) : this(<arguments>) {

  }
}

Inheritance

Classes are final in Kotlin. To inherit from a class that class must be opened.

open class <father_class>(<arguments>)

To inherit from an opened class

class <child_class>(<arguments>) : <father_class>(<arguments>)

Override

To override a father class's function, function must be opened in the father class and overridden in the child class.

open class <father_class>(<arguments>) {
   open fun <function_name>(<arguments>) {

   }
}

class <child_class>(<arguments>) : <father_class>(<arguments>) {
   override fun <function_name>(<arguments>) {

   }
}

Also properties can be overridden in child classes with the same syntax.

Calling parent member

To call parent function or use parent functions use _super_.<name of functions>

To share this page click on the buttons below;