The Programmers Guide To Kotlin - The Basics
The Programmers Guide To Kotlin - The Basics
Monday, 12 June 2017
Article Index
The Programmers Guide To Kotlin - The Basics
Declaring a variable

Var and Val

Although it seemed sensible to dive into functions right at the start because otherwise you can't even make sense of hello world there are some more basic things to look at. It is important to notice that there are two ways to declare a variable var and val. If you write

var myVariable:Int=1;

then you will get a true variable that you can read and write. If you use

val myVariable:Int=1;

then you get a read-only variable which you cannot use on the left of an assignment.

In most cases you should use var for simple types and val for objects. Notice that although you will hear var described as mutable and val as immutable this isn't accurate. All val promises is that the variable is read only. There are ways that what it contains can change.

As to simple types Kotlin has everything you would expect:

TypeBit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

These types are compatible with the types of the same name in Java. You can use decimal, hex and binary constants but octal is banned because o or O looks like a zero and can lead to errors. Some examples are:

0xFF - hex 255
0b10 - binary 2

You also need to know that a Long integer is signified by a trailing L and floats are signified by a trailing F. A nice touch, though not essential, is that you can break up numeric literals with underscores for readability:


You can also use Char for characters encoded using Unicode, just like Java, but you cannot use Char in arithmetic expressions. That is, unlike Java, Char is not a numeric type.

You can also use Booleans with true and false values. The standard Boolean operations are the same as Java:

|| lazy OR
&& lazy AND


! Not

Although this is a little advanced, it is worth mentioning now that while Kotlin has bitwise operation it doesn't associate them with operator symbols as Java does. The bitwise operations work on Int and Long:

Here is the complete list of bitwise operations (available for Int and Long only):

shl() – signed shift left  <<
shr() – signed shift right  >> 
ushr() – unsigned shift right  >>>
and() – bitwise and &
or() – bitwise or |
xor() – bitwise xor ^
inv() – bitwise inversion ~

The symbols listed to the right are the Java operators that do the same job - you can't use them in Kotlin. Of course, you can use all of the these functions as infix operators:  

a or b
1 shr 2 

Null Safety

One of the most important features of Kotlin is that it eliminates the null reference error.

References can be either non-nullable or nullable. If you declare a variable in the usual way you get a non-nullable:

var myvariable:sometype= something

and you cannot set the variable to null as:


throws a compiler error.

If you need a nullable reference then you have to explicitly declare it using ? as in:

var myvariable:sometype?=something

now myvariable can be set to null. 

To avoid accidentally using a null reference the compiler will throw an error if you try to us a nullable without first checking that it is non-null.

For example:

var a:Int=1
var b=a+1

works without any problems as a can never be null, but:

var a:Int?=1
var b=a+1

generates a compiler error because you are adding one to a without checking that it isn't null.

To use a nullable variable you can test for null using an if statement:

 var a: Int? = 1
 var b:Int=1

This compiles and you can be sure that a isn't null when the addition is performed.

Alternatively, if you are accessing a property then you can use the safe call operator ?

For example:

var b=a?.plus(1)

if a isn't null then b is set to 2 but if a is null b is set to null. There are a few small things to notice - b is a nullable type, and nullable simple types are "boxed". That is, the integer a is a full object with methods and properties. In this case we use the plus infix function rather than an operator so that we can use the safe call operator.

If you only want to perform an operation if something is non-null you can use the let method:

a?.let { printlin(a)}

the block of code in the curly brackets is only executed if a is non-null.

There is also the cutely named Elvis operator ?: which will replace a null value with something that is non-null.  For example:


will display the value of a if it is non-null and zero otherwise.

Finally, if you want to throw a null reference exception you can force one using !!. For example:


will either print the value of a or throw an exception if a is null. My guess is that you would only use this to test things.

These null handling features make null a useful, rather than a dangerous, value. For example, if you cast something to a different type you will generate a classcastException if it isn't possible. It is much safer to use the safe cast as? which will return null if the cast isn't possible.


variable as? type

will evaluate to null if the cast to type isn't possible. The advantage of generating a null is that you now have lots of ways of working with it that are guaranteed not to end in an exception.

Notice that a great deal of what makes Kotlin null safe is provided by the compiler, which does its best not to let you write code that works with null values that could result in an exception. If the compiler flags a null problem then don't just make the simplest fix. Try to work out what the role of the null is and if you need it at all. Using non-nullable values is still the safest option.


Programmer's Guide To Kotlin

Now Available as a Print Book


You can buy it from:

USA and World




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 (Coming soon!)
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
  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


To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, FacebookGoogle+ or Linkedin.



The Corpus Christi Prime

This is a clever idea that seems obvious only after you have seen it. Are there other applications waiting to be thought up?

Alexa Gadgets SDK For Voice-Enabled Play

At the same time as launching new Echo products, Amazon has announced Alexa Gadgets and unveiled Echo Buttons, which can be controlled using the Alexa Gadgets SDK and the Gadgets S [ ... ]

More News



blog comments powered by Disqus


Last Updated ( Tuesday, 13 June 2017 )

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