The Programmers Guide To Kotlin - The Class & The Object
The Programmers Guide To Kotlin - The Class & The Object
Written by Mike James   
Monday, 24 July 2017
Article Index
The Programmers Guide To Kotlin - The Class & The Object
Class Members - Methods & Properties
Static Members & Companion Objects

Kotlin is a class-based, object-oriented language and it works in a way that is compatible with Java objects. This doesn't mean that Kotlin does classes in exactly the same way as Java or any other language. In fact. part of the problem in getting to grips with Kotlin classes is that initially they look as if they are just like Java classes - but they aren't. 

They may be compatible with Java classes, but Kotlin offers some significant novel approaches to objects.

 

Programmer's Guide To Kotlin

Now Available as a Print Book

cover

You can buy it from:

USA and World     Amazon.com
Canada            Amazon.ca

UK                Amazon.co.uk
France            Amazon.fr
Germany           Amazon.de
Spain             Amazon.es
Italy             Amazon.it

 

 

Contents
Some Chapters Already Available On The Web

  1. What makes Kotlin Special (Book Only)
  2. The Basics: Variables, Primitive Types and Functions
  3. Control
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy 
    Extract 1 Type and its problems **NEW!**
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
                                               (Coming soon!)
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
    Extract 1 Data Classes  **NEW!**
  13. Exceptions, Annotations & Reflection
  14. Working with Java

Classes

Despite initial appearances, Kotlin is a full object-oriented language. Even though you can have functions at the package level these are in fact bundled up into methods of a default class. 

  • In Kotlin everything is an object. 

Kotlin is fairly traditional in its approach to objects. It restricts inheritance to single inheritance and it supports interfaces with some inherited implementation to get around this restriction. It is also strongly typed, despite managing to make code look as if type isn't important by using type inference. 

The first big shock is how easy it is to create a class and an instance:

   class MyClass{

    }

    var myObject=MyClass()

Notice that you don't need to use new, just use the class name as if it was a function, which of course it is, the constructor.

You can include a type specifier:

var myObject:MyClass=MyClass()

but this isn't the Kotlin idiom as type inference easily supplies the type.

A Kotlin class can have properties and methods, i.e. properties that are functions. Both properties and methods are accessed in the usual way using the dot notation. For example if myMethod is a method that is defined in MyClass you can write:

var myObject=MyClass()
myObject.myMethod()

You can access properties in the same way. 

The Primary Constructor

A class often has multiple constructors to allow it to be customized in different ways. In other languages all of the constructors are generally treated as being of equal importance - with the possible exception of a single parameterless construction which can be called by the system to create a default instance. More importantly they are all defined in the same way as methods within the body of the class declaration - this is not true in Kotlin.

In Kotlin a class can have one primary constructor and as many secondary constructors as you like and the primary constructor seems to be special in some way. 

The primary constructor can be a puzzle to programmers familiar with Java and other languages where constructors are simply methods that have the same name as the class.

Kotlin does away with the redundancy of having to keep on stating the class name within the class definition. In Kotlin the class declaration is also the declaration of the primary constructor and you can include parameters if you want to:

class MyClass(count:Int=0){
}

The primary constructor is convenient but it is limited. You can't place any instructions in the primary constructor because it doesn't have a method body. That is, you can't write something like:

class MyClass(count:Int){
    if(count<0) count=0;
    }

The primary constructor has no method body and the body of the class declaration is for writing class members and secondary constructors. It is not the method body of the primary constructor, even though it might at first sight be mistaken for one. That is, the primary constructor is simply a list of parameters that can be passed when the class is instantiated. 

The question is what can you do with these parameters if the primary constructor has no method body?

The most you can do is to use the primary constructors parameters in property initializers:

class MyClass(count:Int){
     val max=count;
    }

Notice that max is a property of MyClass and nothing to do with the primary constructor, except that it uses a parameter as an initializer.  

This is such a common idiom that Kotlin provides a way to link properties and the parameters in the primary constructor automatically.

If you specify var or val in front of a parameter then it is converted into a read/write or readonly property, complete with initializers. For example:

class MyClass(var count:Int=0){
}

has a read/write property called count initially set to zero.

This idiom makes creating data-only classes, what would be called structs or records in other languages, easy. For example:

class Person(val Name:String,var Address:String)

creates a class with a Name and an Address property.

At the moment it looks as if the primary constructor is limited, but see Initializer Blocks later in this chapter. Adding an initializer block provides a way of executing some code independently of which constructor is called and this includes the primary constructor.

Secondary Constructors

For a great many classes a primary constructor is all that is needed because initializing an instance comes down to creating and initializing some properties. 

If your class needs more initialization than this or if you need to allow alternative forms of initialization then you need to define secondary constructors. 

These are methods prefixed by the keyword constructor - you don't have to give them a name as Kotlin understands constructors. You can also put the keyword constructor in front of the primary constructor if you want to, and you have to if you put any access specifier or annotation on the line. Also notice that you don't have to have an explicit primary constructor - if you don't want one just omit the () and parameters after the class name. Kotlin automatically creates a parameterless primary constructor for you.

For example:

    class MyClass{
            constructor(Name:String){
            println(Name)
        }

    }

is a class without an explicit primary constructor and a single secondary constructor that accepts a single string. 

You can have multiple overloaded constructors and the one that matches the signature of the call will be used.

If you do define a primary constructor then the secondary constructors have to call it using

this(parameters)

and you do have to supply any parameters that don't have defaults, for example:

class MyClass{var Name:String=""){       constructor(Name:String,Address:String):this(Name){
            println(Name)
        }

}

If a secondary constructor delegates to another constructor by calling it then it doesn't have to call the primary, but the other constructor does. 

What all this comes down to is that the primary constructor has to be called somehow.  Also notice that the trick of including var and val to automatically create properties only works with the primary constructor.

 


 kotlinlogo



Last Updated ( Monday, 24 July 2017 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2017 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.