Learning coding means GreatToCode Be more than a Coder ! Greattocode , Join GreatToCode Community,1000+ Students Trusted On Us .If You want to learn coding, Then GreatToCode Help You.No matter what It Takes !


CODE YOUR WAY TO A MORE FULFILLING And HIGHER PAYING CAREER IN TECH, START CODING FOR FREE Camp With GreatToCode - Join the Thousands learning to code with GreatToCode
Interactive online coding classes for at-home learning with GreatToCode . Try ₹Free Per Month Coding Classes With The Top Teachers . Kotlin Tutorials

Kotlin Tutorials

 Complete Kotlin Tutorials :

What is Kotlin?

Kotlin is a modern, trending programming language that was released in 2016 by JetBrains.

It has become very popular since it is compatible with Java (one of the most popular programming languages out there), which means that Java code (and libraries) can be used in Kotlin programs.

Kotlin is used for:

  • Mobile applications (specially Android apps)
  • Web development
  • Server side applications
  • Data science
  • And much, much more!

Why Use Kotlin?

  • Kotlin is fully compatible with Java
  • Kotlin works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
  • Kotlin is concise and safe
  • Kotlin is easy to learn, especially if you already know Java
  • Kotlin is free to use
  • Big community/support

Get Started

This tutorial will teach you the very basics of Kotlin.

It is not necessary to have any prior programming experience.

Kotlin IDE

The easiest way to get started with Kotlin, is to use an IDE.

An IDE (Integrated Development Environment) is used to edit and compile code.

In this chapter, we will use IntelliJ (developed by the same people that created Kotlin) which is free to download from https://www.jetbrains.com/idea/download/.


Kotlin Install

Once IntelliJ is downloaded and installed, click on the New Project button to get started with IntelliJ:

Then click on "Kotlin" in the left side menu, and enter a name for your project:

Next, we need to install something called JDK (Java Development Kit) to get our Kotlin project up and going. Click on the "Project JDK" menu, select "Download JDK" and select a version and vendor (e.g. AdoptOpenJDK 11) and click on the "Download" button:

When the JDK is downloaded and installed, choose it from the select menu and then click on the "Next" button and at last "Finish":

Now we can start working with our Kotlin project. Do not worry about all of the different buttons and functions in IntelliJ. For now, just open the src (source) folder, and follow the same steps as in the image below, to create a kotlin file:

Select the "File" option and add a name to your Kotlin file, for example "Main":

You have now created your first Kotlin file (Main.kt). Let's add some Kotlin code to it, and run the program to see how it works. Inside the Main.kt file, add the following code:

Main.kt

fun main() {
  println("Hello World")
}

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, lets focus on how to run the code. Click on the Run button at the top navigation bar, then click "Run", and select "Mainkt".

Next, IntelliJ will build your project, and run the Kotlin file. The output will look something like this:

As you can see, the output of the code was "Hello World", meaning that you have now written and executed your first Kotlin program!


Learning Kotlin At W3Schools

When learning Kotlin at w3schools.com, you can use our "Try it Yourself" tool, which shows both the code and the result. This will make it easier for you to understand every part as we move forward:

Main.kt

Code:

fun main() {
  println("Hello World")
}

Result:

Hello World
Try it Yourself »

Kotlin Syntax

In the previous chapter, we created a Kotlin file called Main.kt, and we used the following code to print "Hello World" to the screen:

Example

fun main() {
  println("Hello World")
}
Try it Yourself »

Example explained

The fun keyword is used to declare a function. A function is a block of code designed to perform a particular task. In the example above, it declares the main() function.

The main() function is something you will see in every Kotlin program. This function is used to execute code. Any code inside the main() function's curly brackets {} will be executed.

For example, the println() function is inside the main() function, meaning that this will be executed. The println() function is used to output/print text, and in our example it will output "Hello World".

Good To Know: In Kotlin, code statements do not have to end with a semicolon (;) (which is often required for other programming languages, such as JavaC++C#, etc.).


Main Parameters

Before Kotlin version 1.3, it was required to use the main() function with parameters, like: fun main(args : Array<String>). The example above had to be written like this to work:

Example

fun main(args : Array<String>) {
  println("Hello World")
}
Try it Yourself »

Note: This is no longer required, and the program will run fine without it. However, it will not do any harm if you have been using it in the past, and will continue to use it.

Kotlin Output (Print)

The println() function is used to output values/print text:

Example

fun main() {
  println("Hello World")
}
Try it Yourself »

You can add as many println() functions as you want. Note that it will add a new line for each function:

Example

fun main() {
  println("Hello World!")
  println("I am learning Kotlin.")
  println("It is awesome!")
}
Try it Yourself »

You can also print numbers, and perform mathematical calculations:

Example

fun main() {
  println(3 + 3)
}
Try it Yourself »

The print() function

There is also a print() function, which is similar to println(). The only difference is that it does not insert a new line at the end of the output:

Example

fun main() {
  print("Hello World! ")
  print("I am learning Kotlin. ")
  print("It is awesome!")
}
Try it Yourself »

Kotlin Comments

Comments can be used to explain Kotlin code, and to make it more readable. It can also be used to prevent execution when testing alternative code.


Single-line Comments

Single-line comments starts with two forward slashes (//).

Any text between // and the end of the line is ignored by Kotlin (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment
println("Hello World") 
Try it Yourself »

This example uses a single-line comment at the end of a line of code:

Example

println("Hello World")  // This is a comment
Try it Yourself »

Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Kotlin.

This example uses a multi-line comment (a comment block) to explain the code:

Example

/* The code below will print the words Hello World
to the screen, and it is amazing */
println("Hello World")  
Try it Yourself »

Kotlin Variables

Variables are containers for storing data values.

To create a variable, use var or val, and assign a value to it with the equal sign (=):

Syntax

var variableName = value
val variableName = value

Example

var name = "John"
val birthyear = 1975

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear
Try it Yourself »

The difference between var and val is that variables declared with the var keyword can be changed/modified, while val variables cannot.


Variable Type

Unlike many other programming languages, variables in Kotlin do not need to be declared with a specified type (like "String" for text or "Int" for numbers, if you are familiar with those).

To create a variable in Kotlin that should store text and another that should store a number, look at the following example:

Example

var name = "John"      // String (text)
val birthyear = 1975   // Int (number)

println(name)          // Print the value of name
println(birthyear)     // Print the value of birthyear
Try it Yourself »

Kotlin Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x:

Example

var x = 10
Try it Yourself »

The addition assignment operator (+=) adds a value to a variable:

Example

var x = 10
x += 5
Try it Yourself »

A list of all assignment operators:

OperatorExampleSame AsTry it
=x = 5x = 5Try it »
+=x += 3x = x + 3Try it »
-=x -= 3x = x - 3Try it »
*=x *= 3x = x * 3Try it »
/=x /= 3x = x / 3Try it »
%=x %= 3x = x % 3Try it »

Kotlin Comparison Operators

Comparison operators are used to compare two values, and returns a Boolean value: either true or false.

OperatorNameExampleTry it
==Equal tox == yTry it »
!=Not equalx != yTry it »
>Greater thanx > yTry it »
<Less thanx < yTry it »
>=Greater than or equal tox >= yTry it »
<=Less than or equal tox <= yTry it »

You will learn much more about Booleans in the Boolean chapter and Conditions.


Kotlin Logical Operators

Logical operators are used to determine the logic between variables or values:


OperatorNameDescriptionExampleTry it
&& Logical andReturns true if both statements are truex < 5 &&  x < 10Try it »
|| Logical orReturns true if one of the statements is truex < 5 || x < 4Try it »
!Logical notReverse the result, returns false if the result is true

Kotlin is smart enough to understand that "John" is a String (text), and that 1975 is an Int (number) variable.

However, it is possible to specify the type if you insist:

Kotlin Strings

Strings are used for storing text.

A string contains a collection of characters surrounded by double quotes:

Example

var greeting = "Hello"
Try it Yourself »

Unlike Java, you do not have to specify that the variable should be a String. Kotlin is smart enough to understand that the greeting variable in the example above is a String because of the double quotes.

However, just like with other data types, you can specify the type if you insist:

Example

var greeting: String = "Hello"
Try it Yourself »

String Length

A String in Kotlin is an object, which contain properties and functions that can perform certain operations on strings, by writing a dot character (.) after the specific string variable. For example, the length of a string can be found with the length property:

Example

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
println("The length of the txt string is: " + txt.length)
Try it Yourself »

String Functions

There are many string functions available, for example toUpperCase() and toLowerCase():

Example

var txt = "Hello World"
println(txt.toUpperCase())   // Outputs "HELLO WORLD"
println(txt.toLowerCase())   // Outputs "hello world"
Try it Yourself »

Comparing Strings

The compareTo(string) function compares two strings and returns 0 if both are equal:

Example

var txt1 = "Hello World"
var
txt2 = "Hello World" println(txt1.compareTo(txt2)) // Outputs 0 (they are equal)
Try it Yourself »

Finding a String in a String

The indexOf() function returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

Example

var txt = "Please locate where 'locate' occurs!"
println(txt.indexOf("locate"))  // Outputs 7
Try it Yourself »

Remember that Kotlin counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...


Quotes Inside a String

To use quotes inside a string, use single quotes ('):

Example

var txt1 = "It's alright"
var txt2 = "That's great"
Try it Yourself »

String Concatenation

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

Example

var firstName = "John"
var lastName = "Doe"
println(firstName + " " + lastName)
Try it Yourself »

Note that we have added an empty text (" ") to create a space between firstName and lastName on print.

You can also use the plus() function to concatenate two strings:

Example

var firstName = "John "
var lastName = "Doe"
println(firstName.plus(lastName))
Try it Yourself »

String Templates/Interpolation

Instead of concatenation, you can also use "string templates", which is an easy way to add variables and expressions inside a string.

Just refer to the variable with the $ symbol:

Example

var firstName = "John"
var lastName = "Doe"
println("My name is $firstName $lastName")
Try it Yourself »

"String Templates" is a popular feature of Kotlin, as it reduces the amount of code. For example, you do not have to specify a whitespace between firstName and lastName, like we did in the concatenation example.

Note: If you want to create a String without assigning the value (and assign the value later), you must specify the type while declaring the variable:

Example

This works fine:

var name: String
name = "John"
println(name)
Try it Yourself »

Example

This will generate an error:

var name
name = "John"
println(name)
Try it Yourself »

Access a String

To access the characters (elements) of a string, you must refer to the index number inside square brackets.

String indexes start with 0. In the example below, we access the first and third element in txt:

Example

var txt = "Hello World"
println(txt[0]) // first element (H)
println(txt[2]) // third element (l)
Try it Yourself »

[0] is the first element. [1] is the second element, [2] is the third element, etc.

Example

var name: String = "John" // String
val birthyear: Int = 1975 // Int

println(name)
println(birthyear)
Try it Yourself »

You can also declare a variable without assigning the value, and assign the value later. However, this is only possible when you specify the type:

Example

This works fine:

var name: String
name = "John"
println(name)
Try it Yourself »

Example

This will generate an error:

var name
name = "John"
println(name)
Try it Yourself »

Notes on val

When you create a variable with the val keyword, the value cannot be changed/reassigned.

The following example will generate an error:

Example

val name = "John"
name = "Robert"  // Error (Val cannot be reassigned)
println(name)
Try it Yourself »

When using var, you can change the value whenever you want:

Example

var name = "John"
name = "Robert"
println(name)
Try it Yourself »

So When To Use val?

The val keyword is useful when you want a variable to always store the same value, like PI (3.14159...):

Example

val pi = 3.14159265359
println(pi)
Try it Yourself »

Display Variables

Like you have seen with the examples above, the println() method is often used to display variables.

To combine both text and a variable, use the + character:

Example

val name = "John"
println("Hello " + name)
Try it Yourself »

You can also use the + character to add a variable to another variable:

Example

val firstName = "John "
val lastName = "Doe"
val fullName = firstName + lastName
println(fullName)
Try it Yourself »

For numeric values, the + character works as a mathematical operator:

Example

val x = 5
val y = 6
println(x + y) // Print the value of x + y 
Try it Yourself »

From the example above, you can expect:

  • x stores the value 5
  • y stores the value 6
  • Then we use the println() method to display the value of x + y, which is 11

Variable Names

A variable can have a short name (like x and y) or more descriptive names (age, sum, totalVolume).

The general rule for Kotlin variables are:

  • Names can contain letters, digits, underscores, and dollar signs
  • Names should start with a letter
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive ("myVar" and "myvar" are different variables)
  • Names should start with a lowercase letter and it cannot contain whitespace
  • Reserved words (like Kotlin keywords, such as var or String) cannot be used as names

camelCase variables

You might notice that we used firstName and lastName as variable names in the example above, instead of firstname and lastname. This is called "camelCase", and it is considered as good practice as it makes it easier to read when you have a variable name with different words in it, for example "myFavoriteFood", "rateActionMovies" etc.


Kotlin Data Types

In Kotlin, the type of a variable is decided by its value:

Example

val myNum = 5             // Int
val myDoubleNum = 5.99    // Double
val myLetter = 'D'        // Char
val myBoolean = true      // Boolean
val myText = "Hello"      // String
Try it Yourself »

However, you learned from the previous chapter that it is possible to specify the type if you want:

Example

val myNum: Int = 5                // Int
val myDoubleNum: Double = 5.99    // Double
val myLetter: Char = 'D'          // Char
val myBoolean: Boolean = true     // Boolean
val myText: String = "Hello"      // String
Try it Yourself »

Sometimes you have to specify the type, and often you don't. Anyhow, it is good to know what the different types represent.

You will learn more about when you need to specify the type later.

Data types are divided into different groups:

  • Numbers
  • Characters
  • Booleans
  • Strings
  • Arrays

Numbers

Number types are divided into two groups:

Integer types store whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are ByteShortInt and Long.

Floating point types represent numbers with a fractional part, containing one or more decimals. There are two types: Float and Double.

If you don't specify the type for a numeric variable, it is most often returned as Int for whole numbers and Double for floating point numbers.


Integer Types

Byte

The Byte data type can store whole numbers from -128 to 127. This can be used instead of Int or other integer types to save memory when you are certain that the value will be within -128 and 127:

Example

val myNum: Byte = 100
println(myNum)
Try it Yourself »

Short

The Short data type can store whole numbers from -32768 to 32767:

Example

val myNum: Short = 5000
println(myNum)
Try it Yourself »

Int

The Int data type can store whole numbers from -2147483648 to 2147483647:

Example

val myNum: Int = 100000
println(myNum)
Try it Yourself »

Long

The Long data type can store whole numbers from -9223372036854775807 to 9223372036854775807. This is used when Int is not large enough to store the value. Optionally, you can end the value with an "L":

Example

val myNum: Long = 15000000000L
println(myNum)
Try it Yourself »

Difference Between Int and Long

A whole number is an Int as long as it is up to 2147483647. If it goes beyond that, it is defined as Long:

Example

val myNum1 = 2147483647  // Int
val myNum2 = 2147483648  // Long

Floating Point Types

Floating point types represent numbers with a decimal, such as 9.99 or 3.14515.

The Float and Double data types can store fractional numbers:

Float Example

val myNum: Float = 5.75F
println(myNum)
Try it Yourself »

Double Example

val myNum: Double = 19.99
println(myNum)
Try it Yourself »

Use Float or Double?

The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of Float is only six or seven decimal digits, while Double variables have a precision of about 15 digits. Therefore it is safer to use Double for most calculations.

Also note that you should end the value of a Float type with an "F".

Scientific Numbers

A floating point number can also be a scientific number with an "e" or "E" to indicate the power of 10:

Example

val myNum1: Float = 35E3F
val myNum2: Double = 12E4
println(myNum1)
println(myNum2)
Try it Yourself »

Booleans

The Boolean data type and can only take the values true or false:

Example

val isKotlinFun: Boolean = true
val isFishTasty: Boolean = false
println(isKotlinFun)   // Outputs true
println(isFishTasty)   // Outputs false 
Try it Yourself »

Boolean values are mostly used for conditional testing, which you will learn more about in a later chapter.


Characters

The Char data type is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c':

Example

val myGrade: Char = 'B'
println(myGrade)
Try it Yourself »

Unlike Java, you cannot use ASCII values to display certain characters. The value 66 would output a "B" in Java, but will generate an error in Kotlin:

Example

val myLetter: Char = 66
println(myLetter) // Error

Strings

The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:

Example

val myText: String = "Hello World"
println(myText)
Try it Yourself »



Arrays

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Type Conversion

Type conversion is when you convert the value of one data type to another type.

In Kotlin, numeric type conversion is different from Java. For example, it is not possible to convert an Int type to a Long type with the following code:

Example

val x: Int = 5
val y: Long = x
println(y) // Error: Type mismatch 
Try it Yourself »

To convert a numeric data type to another type, you must use one of the following functions: toByte()toShort()toInt()toLong()toFloat()toDouble() or toChar():

Example

val x: Int = 5
val y: Long = x.toLong()
println(y)
Try it Yourself »

Kotlin Operators

Operators are used to perform operations on variables and values.

The value is called an operand, while the operation (to be performed between the two operands) is defined by an operator:

OperandOperatorOperand
100+50

In the example below, the numbers 100 and 50 are operands, and the + sign is an operator:

Example

var x = 100 + 50
Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and a variable:

Example

var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)
var sum3 = sum2 + sum2 // 800 (400 + 400)
Try it Yourself »

Kotlin divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

OperatorNameDescriptionExampleTry it
+AdditionAdds together two valuesx + yTry it »
-SubtractionSubtracts one value from anotherx - yTry it »
*MultiplicationMultiplies two valuesx * yTry it »
/DivisionDivides one value from anotherx / yTry it »
%ModulusReturns the division remainderx % yTry it »
++IncrementIncreases the value by 1++xTry it »
--DecrementDecreases the value by 1--xTry it »

Note: You will learn more about Data type scroll down.

Post a Comment

0 Comments

•Give The opportunity to your child with GreatToCode Kid's • Online Coding Classes for Your Kid • Introduce Your kid To the world's of coding
•Fuel You Career with our 100+ Hiring Partners, Advance Your Career in Tech with GreatToCode. •Join The Largest Tech and coding Community and Fast Forward Your career with GreatToCode. •10000+ Learner's+ 90 % placement Guarantee. • Learning Coding is Better with the GreatToCode community .
•Greattocode Kid's •GreatToCode Career •GreatToCode Interview •GreatToCode Professional •GreatToCode for schools •GreatToCode For colleges •GreatToCods For Businesses.
Are you ready to join the millions of people learning to code? GreatToCode Pass is your one-stop-shop to get access to 1000+ courses, top-notch support, and successful job placement. What are you waiting for? Sign up now and get your future in motion with GreatToCode Pass.