Press enter to see results or esc to cancel.

kotlin Tutorial: Beginners Guide with Examples

Share this
()

Introduction to Kotlin Tutorial

In the first part of this kotlin tutorial, you will be introduced to all the basic syntax of kotlin programming language.


A little introduction.

Version 1.0 of Kotlin is only available from 2016, but it is already highly appreciated because it represents a valid alternative to Java.

Allot of programmers have already adopted this language because of the small number of runtime errors it produces, especially the dreaded NullPointerExceptions.

Kotlin is basically Java-based: Meaning Kotlin can run on any of the Javabased environments.  Kotlin is converted into bytecode, which can be read by a Java Virtual Machine (JVM).


Kotlin Hello World Syntax

In Kotlin, the “Hello World” program, will consist of these 3 simple lines of code:

fun main () {
println( "Hello world!" )
}

Here we can see:

  • The main() function, where we write our output statement.
  • A call to the println() function

There is nothing else to add (import, classes, etc.). This is a complete program that will compile as it is written.


Topic: kotlin Tutorial: Beginners Guide with Examples

Kotlin Comments

kotlin comments

All the programming languages have a way of inserting in some text that will be ignored by the compiler, but useful to the programmers/managers of the code.

Unlike java, There are 3 different types of comments in Kotlin language.

  • Single line comment
  • Multi-line comment
  • Nested comment

Single-Line Comments

Denoted with double slash (//), all text that will follow on the same line of code will be ignored by the compiler

// Single-line Kotlin comment
val x = 4 * 10
val y = 4 // * 10
println ( x ) // Will print 40
println ( y ) // Will print 4
// kotlin tutorial for beginners by coding180.com

Multi-Line Comments

Multiline comment (otherwise known as documentation comment) contains text that can expand multiple lines, it starts with  /*  and ends with */. Any text in between these symbols will be ignored by the compiler.

Nested Comments

Unlike C and Java, it is also possible to nest such comments.

/ *
I'm a multi-line comment in Kotlin.
/ *
I am a multi-line comment embedded in another multi-line comment.
* /
I'm still a multi-line comment ( but not in C or Java ) .
* /

 

If it was in the case of Java or C, the comment would be made up only of the first 5 lines of the example, leaving the last 2 lines not commented, and generating (at least) a compilation error.


Kotlin Variables and Constant

Variables and constants in Kotlin must be explicitly declared before they are used. Constants are declared with the val keyword, while variables are declared with var.

  • val – Immutable reference and their values cannot be changed.
  • var – Mutable, value can be changed during the program execution.

Here is an example with a variable and a constant in Kotlin:

 

val loginAttemtLimit= 5
var loginAttempt= 0

 

loginAttemtLimit is constant, and therefore cannot be changed.  instead, loginAttempt is variable, so we can update it every time the user tries to login.

If you declare a variable by assigning a value to it (e.g val loginAttemtLimit = 5), the type is said to be inferred by the compiler, that is the compiler (and we too), will know exactly the type that the variable must assume, knowing the type of the value. In our case, “int” type.

If the variable is declared without assigning a value to it, the type cannot be inferred, and must, therefore, be made explicit.

val loginAttemtLimit: Int
var loginAttempt: Int

Alternatively, you can explicitly write the type for additional clarity even when you assign it a value

val loginAttemtLimit: Int = 5
var loginAttempt: Int = 0

Topic: kotlin Tutorial: Beginners Guide with Examples

Kotlin Data Types

Kotlin works with specific types of variables and classes.

In Kotlin, each type consists of an object, which makes it slightly different from Java. Click To Tweet

While the older programming languages must first package primitive types into a wrapper class to make them objects.

In Kotlin, on the other hand, similarly to C#,  we do not have primitive types. This means that in Kotlin any type we are dealing with consists of an object.

So even for variables of basic types, we can call methods and properties.

The basic types in Kotlin consist of

  • Numbers: (Byte, Short, Int, Long, Float, Double)
  • Characters (Char)
  • Boolean (Boolean)
  • Arrays (Array)
  • Strings

Numbers

In Kotlin, it is possible to insert numbers without specifying the type, the compiler understands that these are numeric values.

Commas are indicated by dots.

Hexadecimal numbers can also be used.

For better readability, the decimal separators can be displayed using low dashes.

Kotlin knows different types of numbers, each of which can have a different maximum size:

  • Long: 64 bits
  • Int: 32 bit
  • Short: 16 bit
  • Byte: 8 bits
  • Double: 64 bits
  • Float: 32 bits

Double and Float are floating-point numbers that behave differently from fixed-point numbers in complex calculations.

It is possible to convert a number of one type to another.

 

val myInt = 600 
val myLong = myInt.toLong()

The toLong() command converts the Int value to a Long value. The command works the same way for other types of numbers.

In Kotlin, numbers are treated similarly to Java, except for 3 points:

  1. There are no implicit conversions
  2. The “literals” are different in some cases
  3. Characters are not numbers

IMPLICIT CONVERSIONS

Implicit conversions between numbers are not allowed even when there is no loss of value, i.e. when making an implicit cast from a Float (32-bit) to a Double (64-bit), or from an Int (32-bit ) to a Long (64-bit).

So this code will produce a compilation error:

 

val x: Float = 1 . 0f
val y: Double = x // Type mismatch. Required: 'Double' Found: 'Float'
// kotlin tutorial for beginners
// by coding180.com

 

LITERAL

Literals are a notation in computer science to represent a value fixed in the source code. For strings, in Kotlin we have double-quotes.

For numbers, there are slightly different notations representing different types.

The source code below shows the literals of int, long, float and double Numeric type.

// Kotlin tutorial for beginners
// coding180.com
                  
// Integer (32-bit)
val a = 100 // decimal notation
val myHex = 0xFF // hexadecimal notation
val myBin = 0b00001011 // binary notation


println ( a ) // 100
println ( myHex ) // 255
println ( myBin ) // 11


// Long (64-bit)
val b = 1234567890123 // too large for Int, Long by default
val c = 100L // always 100, but Long
println ( c ) // 100


// Float (32-bit)
val d = 10 .0f // f before the decimal


// Double (64-bit)
val e = 10.0 // classical notation
val f = 123 .5e10 // exponential notation (= 123.5 * 10 at 10)


print ( f ) // 1.235e12
print ( f. toLong ( ) ) // 1235000000000

In addition, you can use underscore (_) to separate numbers for clarity

val cost = 1_000_000
val creditCardNumber = 1234_5678_9123_4567L

Topic: kotlin Tutorial: Beginners Guide with Examples

CHARACTERS

Kotlin characters are represented by the keyword Char, and their literal is denoted by single quotes.

val myChar = 'a'
println (myChar) // a

 

Unlike other languages, it is not possible to use ASCII or Unicode directly by using numbers to instantiate or verify a character, even if it is possible to use an explicit cast.

var myChar: Char

myChar = 'A' // OK
myChar = 65 // Error
myChar = 65.toChar() //OK ('A')

 

String Type

Strings are represented by the String type. When we talk about string we mean a whole word or phrase, or a string of characters.

To use them in Kotlin, we put the text in double-quotes.

If you want to insert multiple lines of text, you need three double quotes both at the beginning and at the end.

var message: String = "Hello world!"
val multipleLine=
"""
Hi, I'm a very long string
and with multiple lines.
"""
// kotlin tutorial for beginners by coding180

As in many other programming languages, even Kotlin supports sequences escape: prepending a backslash in front of a character indicating that this does not belong to the actual string and it should be treated as a control character.

A control character is a non-printable character that is served to instantiate a particular action.

With the help of the backslash, you can also insert control character in the string to carry out a particular action.

These are the possible escape sequences:

  • tab: \t
  • backspace: \b
  • newline: \n
  • carriage return: \ r
  • single quotation mark: \’
  • double-quote: \ “
  • backslash: \\
  • dollar sign: \$

The dollar sign is used in strings to insert metacharacters, which we can use to print the value of a variable.

Metacharacter is a type of character that adds a special meaning to a program, eg shell, regular expression.

The metacharacter is then replaced in the output by an actual value.

val author = "Robort Gabriel"
val myString = "My name is $author"

Topic: kotlin Tutorial: Beginners Guide with Examples

Boolean

Booleans are represented by the Boolean type, and a Boolean value can only be true or false.

Operators for Boolean include:

  • || for OR
  • && for AND
  • ! NOT (true or false)

 

fun main() {
    // AND
    println(true && true) // true
    println(true && false) // false
    println(false && true) // false
    println(false && false) // false


// OR
    println(true || true) // true
    println(true || false) // true
    println(false || false) // false


// NOT
    println(!true) // false
    println(!false) // true
// kotlin tutorial for beginners by coding180
}

Both the AND and OR operators are also called “short-circuits”. This means that if the first expression evaluated is true, the second is not even evaluated.

Here is an example on the  short-circuit:

// Function that returns a Boolean to be used in conditions
fun print(message: String): Boolean {
    println(message)
    return true
}

fun main() {
    println(false && print("first case"))
    println(true && print("second case"))


    println(true || print("third case"))
    println(false || print("fourth case"))


    println(print("fifth case") || print("sixth case"))
    println(print("seventh case") && print("eighth case"))
}
// kotlin tutorial for beginners by coding180.com
Output:
false
second case
true
true
fourth case
true
fifth case
true
seventh case
eighth case
true

How useful was this Lesson?

Click on a star to rate it!

Average rating / 5. Vote count:

Be the first to rate this post.!

As you found this post useful...

Follow us on social media!

We are sorry that this lesson was not useful for you!

Let us improve this lesson!

Tell us how we can improve this lesson?

Share this

Pages:   1 2 3