Blog
16 BEST Note Taking App for Mac (2021)
Note-taking apps are the online notebooks, and because they're digital, you can do much more than...
Kotlin is an open-source statically typed programming language that runs on Java Virtual Machine (JVM). It combines Object Oriented Programming (OOPs) and functional programming in unrestricted, self-sufficient, and distinctive platforms. It also allows the twinning of functionalities by miniature codes. Kotlin is a general-purpose programming language which was designed by JetBrains.
In this Kotlin Tutorial for beginners, you will learn Kotlin programming language basics:
Here, are important landmarks from the history of Kotlin:
Year | Event |
2016 | Kotlin v1.0 was launched |
2017 | Announcement of Google on the first-class support of kotlin in android |
2018 | Kotlin v1.2 comes with add on distributing codes between JVM and JavaScript |
2019 | Google announced Kotlin as its preferred programming language for Android Application Developers |
Here, are some important reasons why Kotlin is used widely:
Here are a few features of the Kotlin that will make you sure of the progress path of the programming language.
Kotlin is an OOPs-based programming language where code line can be trimmed up to 40 % that which makes Kotlin an ideal choice for software or web development.
Kotlin for Android utilizes JVM and combines the features of OOPs and functional-oriented programming.
it is easy to compile the code when working with Kotlin that results in better performance for android development, and it will also explain which type of data function can be used in the entire code.
Kotlin can support a variety of extension functions without making any changes to the code. it helps in making existing code more appealing and magnificent for developers.
For Example:
Fun String.removeFirstLastChar(): String = this.substring(1, this.length -1)
This code will assist in trimming down the first and the last character of the string, we can apply it as:
Val string1 = "Today is cloudy." Val string2 = string1.removeFirstLastChar()
In Kotlin, the system distinguishes between null references and not null references as shown in below Kotlin example.
For example, a String variable cannot hold null:
Var string1: String = "Today is Sunday" String1 = null // compilation error To permit null, we can adjoin the nullable variable : Var string2: String? = "Today is Sunday" String2 = null print(string2)
Kotlin code can be used by Java, and Java codes can be used with Kotlin. So, if you have knowledge about OOPS programming, it is easy to switch to Kotlin's development. Also, if there are some applications written in Java, then they can be used with Kotlin's environment.
Like Java, Kotlin code can also be written using IDE or using the command-line interface. It is easy to work with IDE, and syntax errors are also reduced dramatically. At the same time, when you are working with a command-line interface, code has to be compiled first.
Smart casting basically helps to cut down the application costs and improves its speed or performance. It works on managing the efficiency of code using type casting or immutable values.
For example, if the string is identified, then it's length and count and can be found with the help of Smart Cast function:
Val string1: Any = "Today is Monday" when(string1) { is String -> string1.length Is Int -> string1.inc() }
Kotlin is preferred by enterprises because of its lost cost of adoption. Most importantly, it is easy to learn by developers, especially having a programming background.
Following are the steps which helps help you in setting up a working environment by installing Kotlin.
As we have discussed earlier that Kotlin is based on Java, so you have to install Java first when planning to adopt Kotlin. Refer our Java Installation Tutorial.
Luckily, there are multiple Java IDEs to choose from. Here we have given download links to make things a little easier for you.
In this Kotlin tutorial, we will use Eclipse.
For Installing Kotlin in Eclipse, go to the Help section in Eclipse and click the Eclipse Marketplace option.
Now, Type the Kotlin keyword into the search box. Click on Go option to list the plugin. It will give you a link of Kotlin plug-in, you need to install the plug-in from the given link.
Please restart the Eclipse IDE, once the installation is complete. You can find a shortcut icon in the top right corner of Eclipse IDE. It is a quick access method.
Another way of accessing Kotlin in Eclipse IDE is, go to the Windows, Perspectives, Open Perspectives, then choose Others option. Here, you can check a list of plugins installed later, as given below.
Once, you have verified the Kotlin installation, let us create the first Kotlin program in the next step.
Start with your first Kotlin project. From the File menu, choose the New option, then select others and start with a new Kotlin project from the list.
Now, you have to define a name for the project, and you are ready to work with Kotlin.
With these simple steps, it is easy downloading Eclipse and Kotlin on your system and write your first Kotlin program right away.
A well-built architecture is important for an application to scale up its features and meet the expectations of the end-user base. Kotlin has its own peculiar and distinctive architecture to allocate the memory and to get quality outcomes for the developers and end-users.
Kotlin's coroutines and classes architect the core in such a way to produce less boilerplate code, amplify the performance, and reinforce the efficiency. There are a variety of scenarios where the kotlin compiler can react differntly, especially whenever it is earmarking various kinds of languages.
Architecture of Kotlin
In the architecture diagram, it is clear that code execution is done in three easy steps.
When a couple of byte coded file operates on JVM, they kindle the mutual communication among themselves, which is why the feature in Kotlin called Interoperability for java ook birth
The transpiring of Kotlin to JavaScript happens when Kotlin targets JavaScript.
When the JavaScript's target is chosen, any code of Kotlin that is a part of the library that sails with Kotlin is than spilled with JavaScript. However, the Java Development Kit(JDK) or any java library used is excluded.
A non-Kotlin file is not taken into consideration during such operation. While targeting JavaScript .kt file is converted into ES5.1 by Kotlin compiler to generate a consistent code for JavaScript. Kotlin compiler endeavors an optimal size output, interoperability with existing module, same functionality with the standard library, and output that is JavaScript readable.
It is clear from the discussion that Kotlin Compilers can create a more efficient, competent, and independent code that further results in a high-performing software product.
Variables are used to store data to be manipulated and referenced in the program. It is fundamentally a unit of storing data and labeling it waits for an expository alias so that the program is simple to read and easy to understand. In other words, we can say that variables are the containers to collect information.
In Kotlin, all the variables should be declared. However, if any variable is not declared, then it pops out to be a syntax error. Also, the declaration of the variable determines the type of data we are allowing to store in the variable. In Kotlin, variables can be defined using val and var keywords. Here is the syntax of declaring variables in Kotlin:
Var day = "Monday" Var number = 3
Here, we have declared the local variable day whose value is "Monday' and whose type is String and another local variable number whose value is 3 and whose type is Int because here the literal is of the type integer that is 3.
Local variables are customarily declared and initialized simultaneously. We can also perform certain operations while initializing the Kotlin variable.
We can perform an operation on the variable of the same data type, as in here num1 and num2 both are of the same data type that is Int, whereas day is of the string data type. Ergo, it will show an error. Here is one another technique how can you define variables in Kotlin.
var day : String = "GURU99" var num : Int = 100
Let see how var and val keywords are different from each other.
Var is like a generic variable used in any programming language that can be utilized multiple times in a single program. Moreover, you can change its value anytime in a program. Therefore, it is known as the mutable variable.
Here is an example of mutable variable in Kotlin:
var num1 = 10 Var num2 = 20 Num1 = 20 print(num1 + num2) // output : 40
Here the value of num1 that is 20, is overwritten by the previous value of num1 that is 10. Therefore the output of num1 + num2 is 40 instead of 30.
Val is like a constant variable, and you cannot change its value later in the program, which neither can be assigned multiple times in a single program and can be used only once in a particular program. Ergo, it is known as an immutable variable.
Here is an Kotlin program example of immutable variables in Kotlin:
Val num1 = 10 Var num2 = 20
Here, the value of num1 that is 10 cannot be overwritten by the new value of num1 that is 20, as it is of val type that is constant. Therefore, the output is 30 instead of 40.
Note: In Kotlin, immutable variables are preferred over mutable variables.
Data types are set of relatable values and describe the operations that can be operated on them. Similar to other programming languages, Kotlin also has its predefined set of data types like Int, Boolean, Char, Double, etc.
In Kotlin, every data type is considered as an object.
Now in this Kotlin basic Tutorial, let's dive deeper into the predefined data types used in Kotlin.
Kotlin serves a set of built-in data types known as numbers, which are sub-categorize as Integers and Floating-Point Numbers.
Integers are the category of numbers that has four types:
Type | Size (bits) | Min value | Max value |
Byte | 8 | -128 | 127 |
Short | 16 | -32768 | 32767 |
Int | 32 | -2,147,483,648 (-231) | 2,147,483,647 (231 - 1) |
Long | 64 | -9,223,372,036,854,775,808 (-263) | 9,223,372,036,854,775,807 (263 - 1) |
Floating Point Numbers are the non-Integer numbers that carry some decimal values.
Float: Float is a 32- bit single-precision floating-point value.
Example: var: Float x = 3.25600
Double: Double is a 64- bit double - precision floating point value.
Example: var: Double y = 2456.345587
Booleans data type in Kotlin is significant to represent the logical values. There are only two possible values in Boolean that is either true or false.
For Example : val day = true
Val day2 = false
Characters in Kotlin are represented with the help of the keyword called char. In Kotlin, single quotes represent the declaration of char. In java, char are sometimes used as numbers that is not possible in kotlin.
For Example :
val onechar = 'x' print(onechar) // output : x Val onedigit = '7' print(onedigit) // output : 7
Type Conversion is a procedure of converting one type of data variable into another data type variable. It is enormously, also known as Type Casting.
Eminently, in Java, implicit type of type conversion or implicit type of typecasting of a smaller data type to larger data type is supported.
For Example : int abc = 15; Long bcd = abc; // compiles successfully
However, in kotlin, implicit conversion of a smaller data type to a larger data type is not at all supported that is int data type cannot be converted into long data type implicitly.
For Example : var abc = 15 Val bcd : Long = abc // error
However, In Kotlin, type conversion is done explicitly. Here comes the guidance of helper functions that guides the conversion of one data type variable to another.
There are certain helper function which are pre - owned for the conversion of one data type to another :
toInt()
toByte()
toShort()
toChar()
toLong()
toFloat()
toDouble()
For Example : var abc = 15 Val bcd : Long = abc.toLong() // compiles successfully
Operators are momentous and special characters or symbols that assures the operations in operands that have variables and values. In Kotlin, there is a set of operators that are used in different operations like arithmetic operations, assignment operations, comparison operations, etc.
Arithmetic operators are used for addition, subtraction, multiplication, division, and modulus.
Operator | Meaning |
+ | Addition (also used for string concatenation) |
- | Subtraction Operator |
* | Multiplication Operator |
/ | Division Operator |
% | Modulus Operator |
For Example :
var x = 10 var y = 20 var z = ( ( x + y ) * ( x + y ) ) / 2
Here the output of the following code is 45.
Comparison operator is used to compare two values, two variables or two numbers. It is used with the greater than symbol( > ), less than symbol( < ) and equal to symbol( ==), not equal to symbol( != ), greater than equal to symbol( >= ), less than equal to symbol(<= ). It always results in true or false.
For Example :
var x = 10 Var y =20 Var z = x < y // Output : true Var w = x > y // Output : false Var m = x == y // Output : false
Assignment Operators are used to assign the arithmetic operated values. It is used with the symbols like +=, -=, *=, /=, %=.
For Example:
var x = 10 var y = 20 var x + = y // Output : 30 Var y - = x // Output : 10 Var x * = y // Output : 200
Increment and decrement operators are used to increment and decrement the values of the variable or number. It is used with the help of symbols like ++ and —.
There are two types of increment and decrement that are pre-increment ++a, post-increment a++, pre decrement --b, post decrement b--.
For Example :
var a = 10 var b = 20 var c = a++ // Output: 11 var d = b— //Output : 19
An Array is the homogenous set of data types and is one of the most fundamental data types which is used to store the same types of data in the contiguous memory location. An Array is significant for the organization of data in any programming language so that multiple data stored ant a single place is easy to search or sort.
In Kotlin, arrays are a mutable collaboration of the same data types rather than being native data types.
Here are certain properties of an array in Kotlin
In Kotlin, an array can be defined in two different methods
In Kotlin, there is a major usage of library functions. One such library function is arrayOf() function, which is used to define an array by passing the values of the variables to the function.
For Example : Implicit type declaration of array using arrayOf() function
val x = arrayOf(1,2,3,4,5,6,7,8,9)
For Example : Explicitly type declaration of array using arrayOf() function.
Val y = arrayOf<Int>(1,2,3,4,5,6,7,8,9)
In Kotlin, there is a class with the name of Array. Therefore, it is feasible to use an array of the constructor to create an array. The array in constructor holds two major parameters.
The function where an array index is acceptable to return the initial value of the index.
For Example :
val abc = Array(7 , { i -> i*1})
Here, the value of array is 7 and lambda expression is used to initialize the values of the element.
There are also various methods to access and modify the arrays using certain functions. Therefore, there are two member functions get() and set(), which are used to access class array's objects.
For Example :
val x = arrayOf(10,20,30,40,50,60,70,80,90) val y = x.get(0) // Output 10
Here, the output is 10 since the value at the index 0 of array is 10
Note : get() takes only single values
For Example:
val x = arrayOf(10,20,30,40,50,60,70.80.90) val y = x.set(2, 3) //
Output : 30 40
Here, the output is 30 and 40 since the value at the index 2 of array is 30 and at index 3 it is 40.
Note: set() takes multiple values of an array.
A string is a basic data type in any programming language. A string is nothing but a sequence of characters. The String class represents character strings. In Kotlin, all strings are objects of the String class, which means string literals are implemented as instances of the class.
Syntax:
Val myString = "Hey there!"
A collection contains several objects of a similar type, and these objects in the collection are called elements or items. Collection can help to store, retrieve, manipulate, and aggregate data.
Immutable collection
This type of collection support read-only functionalities. One cannot modify its elements.
Methods include:
Mutable Collection
It supports both read and write functionality.
Methods include
Functions in any programming language is a group of similar statements which is designated to perform a specific task. Functions allow a program to break it into various small code blocks. This division of code increases the readability of code, reusability of code, and makes a program easy to manage.
As Kotlin is known as a statically typed language. Here, the 'fun' keyword is used to declare a function. In Kotlin, there are two types of functions which solely depends upon its availability in the standard library or user definition. They are:
Kotlin Functions
Now, let us discuss them in detail with Kotlin code examples.
They are built-in library functions that can be defined implicitly and available for use.
For example 2:
fun main(args: Array<String>){ var number = 9 var result = Math.sqrt(number.toDouble()) print("$result") }
Output:
3.0
sqrt() is a function defined in the library which returns the square root of a number.
print() function prints message to a standard output stream.
As the name suggests, these functions are usually created by users, and they can be used for advanced programming.
Here, functions are declared using the 'fun' keyword.
Example 3 :
fun functionName(){ //body of the code }
Here, we call the function to run codes inside the body functionName()
Kotlin function examples:
fun main(args: Array<String>){ sum() print("code after sum") } fun sum(){ var num1 =8 var num2 = 9 println("sum = "+(num1+num2)) }
Output:
sum = 17
code after sum
Exception in programming is defined as a runtime problem which occurs in the program, leading it to terminate. This issue can occur due to less memory space, array out of bond, conditions like division by zero. To curb these types of issues in code execution, exception handling is used.
Exception handling is defined as the technique which handles the runtime problems and also maintains the program flow during execution.
Kotlin uses the 'throw' expression to throw an exception object. Here all exception classes are descendants of class Throwable.
Throw MyException("throws exception")
There are four types of exceptions in exception handling. They are:
In try-catch block in exception handling, try block encloses the code, which may throw an exception and catch block catches the expression and handles it.
Syntax of try catch block:
try{ //code with exception }catch(e: SomeException){ //code handling exception }
Syntax of try with finally block
try{ //code with exception }finally{ // code finally block }
In Kolin, finally block always checks whether the exception is handled or not, making it a very important statement of exception handling.
Example 4:
In this code snippet, the exception occurs, and it is handled.
fun main (args: Array<String>){ try { val data = 9/ 0 println(data) } catch (e: ArithmeticException) { println(e) } finally { println("finally block executes") } println("write next code") }
Output:
java.lang.ArithmeticException: / by zero finally block executes write next code
Throw block throws an explicit exception. Moreover, it is used to throw custom exceptions.
Syntax:
Throw SomeException() Throw SomeException()
Example:
fun main(args: Array<String>) { try{ println("Exception is not thrown yet") throw Exception("Everything is not well") println("Exception is thrown") } catch(e: Exception){ println(e) } finally{ println("You can't ignore me") } }
Output:
The types of systems that support Kotlin majorly distinguishes among the references that can carry nullable references, and the ones cannot carry nullable references. Kotlin is a null safety language aimed to eliminate the null pointer exception or null reference from the code, which is deliberately known as A Billion Dollar Mistake.
The most conventional stumbling block of many programming languages is that while accessing a member of a null reference, it results to be a NullPointerException, which could be because of !! operator or this constructor used somewhere else and passed at another point of code. The nullable property requires confirmation for the null check every time prior to its utilization.
In Kotlin, the system distinguishes between null references and not null references.
For example, a String variable cannot hold null:
Example 5:
fun main(args: Array<String>){ var x: String = "GURU99 is the only place where you will get maximum technical content!" // Not Null by default println("x is : $x") // You cannot assign null variable to not-nullable variables // a=null // it will give compilation error var y: String? = "Thanks for visiting GURU99" // Nullable Variable println("y is : $y") y = null println("y is : $y") }
Output:
The object-oriented programming approach allows a complex code snippet to divide into smaller code blocks by creating objects. These objects mutually share two characteristics: state and behavior.
Here are some of the OOPs elements that we are going to discuss with Kotlin code examples:
The first before creating an object, we need to define a class that is also known as the blueprint for the object.
Syntax:
class ClassName { // property // member function ... .. ... }
While defining a class, we only define the specifications for the object, no other parameter like memory or storage is allocated.
Syntax:
var obj1 = ClassName()
A constructor is a way to initialize class properties. It's a member function called when an object is instantiated. But in Kotlin, it works differently.
There are two types of constructors in Kotlin:
Primary constructor: Optimized way to initialize a class
Syntax:
class myClass(valname: String,varid: Int) { // class body }
Secondary constructor: Helps to add initialization logic
Inheritance occurs when some properties of the parent class are acquired by the child class. Inheritance is allowed when two or more classes have the same properties.
Syntax:
open class ParentClass(primary_construct){ // common code }class ChildClass(primary_construct): ParentClass(primary_construct_initializ){ // ChildClass specific behaviours }
An abstract class is a class that cannot be instantiated, but we can inherit subclasses from them. 'abstract ' keyword is used to declare an abstract class.
Example 6:
open class humanbeings { open fun Eat() { println("All Human being Eat") } } abstract class Animal : humanbeings() { override abstract fun Eat() } class Cat: Animal(){ override fun Eat() { println("Cats also loves eating") } } fun main(args: Array<String>){ val lt = humanbeings() lt.Eat() val d = Cat() d.Eat() }
Output:
Note-taking apps are the online notebooks, and because they're digital, you can do much more than...
Video converter is used when you cannot open a video of a certain format. It is also used when you...
DAW (Digital Audio Workstation) is an application or electronic device used for recording,...
A bivariate relationship describes a relationship -or correlation- between two variables, and . In...
CCleaner is a utility software that clears your online tracks, frees up space, and helps you...
What is Continuous Monitoring? Continuous monitoring is a process to detect, report, respond all...