Can I use Kotlin for web development?

Kotlin tutorial: the first steps with the new programming language

Version 1.0 has only been available since 2016, but is already highly regarded: Kotlin, an alternative to Java. The object-based programming language comes from JetBrains, a Czech software development company. She convinces many with her slim character and because it doesn't produce runtime errors that often - especially not the dreaded ones NullPointerExceptions. Kotlin is particularly popular when developing Android apps. But the young programming language is also enjoying enormous popularity as a starting point for JavaScript applications.

Kotlin is closely based on Java: Although the two programming languages ​​are not compatible with each other, Kotlin is transformed into bytecode, which in turn can be read by a Java Virtual Machine (JVM).

Instructions for Kotlin - with examples

To get started with Kotlin, the compiler can be downloaded from the official website. It is easier with a development environment (IDE): IntelliJ IDEA (also from JetBrains), Eclipse (with the appropriate plug-in), NetBeans and Android Studio can handle Kotlin, for example.

Packages

At the beginning of a project, you import the packages that you need to implement your project. You also define the package that you are currently working on. Packages contain classes and functions.

To avoid problems with the same name, you can use packages in Kotlin with as rename. The Naming of the packages does not have to follow the directory structure in which they can be found. For the sake of clarity, however, this procedure is still recommended.

Kotlin automatically loads the most important packages into every project.

In contrast to Java, with Kotlin you can also import individual functions from other packages. To do this, enter the correct path:

The function can then be used as normal.

Lines of code in Kotlin do not have to be marked with a mark - e.g. B. a semicolon - to be completed.

variables

Kotlin knows two different types of variables: Those that can only be read and are fixed are marked with val initiated. You will guide others whose value can be changed in the course of the program var a.

In contrast to the fixed name, the age can be adjusted, for example in a function.

In this example, Kotlin set the type of the value of the variable itself. It is also possible to specifically label these basic types.

Basic types

Kotlin works with certain types for variables and classes. Each type is an object, which is a bit different from Kotlin from Java. While the older programming language first had to wrap primitive types in a wrapper so that they behave like objects, this is not necessary with Kotlin. All types are really objects here.

Numbers

In Kotlin you can insert numbers without a specific marking: the compiler understands that they should be numerical values. Commas are realized with periods. If you want, you can also use hexadecimal numbers. Thousands separators can be displayed with underscores for better readability. Kotlin knows different types of numbersall of which can have a different maximum size:

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

Double and float are Floating point numbersthat behave differently than the fixed-point numbers in complex calculations. Like all types, you can mark numbers concretely in your code.

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

The command toLong converts the int value to a long value. The command works in the same way, modified for the other types of Numbers.

String

A string consists of words or entire sentences, i.e. strings of characters. To use this in Kotlin, put what is written in double quotes. If you want to include several lines of text, three double quotation marks are required at the beginning and at the end (raw string).

As in many other programming languages, Kotlin uses Escape characters possible: Use a backslash to mark a character that does not belong to the actual string but is to be treated as a control character. Conversely, the backslash can also be used to insert characters into the string that actually have a different meaning in Kotlin. The following escape characters are possible:

  • \ t: Tab
  • \ b: backspace
  • \ n: New line
  • \ r: Carriage Return
  • \ ': Single quotation mark
  • \ ": Double quotation mark
  • \: backslash
  • \ $: Dollar sign

The dollar sign is used in strings to placeholder to use. You can define this as a variable in a previous step. The placeholder is then replaced by an actual value in the output.

Characters

In addition to strings, Kotlin also provides the special character data type for individual characters. Instead of putting them in double quotes, one uses single quotes.

Boolean

The Basic Type Boolean returns a truth value that either true (true) or wrong (false) can be.

Arrays

In Kotlin, an array is one Collection of data. You form an array with arrayOf () or Array (). The first function is simple:

 

This is how you create an array with the digits from 1 to 5. In these collections you can also use other types how strings and booleans are accommodated - even mixed. If you want to limit the array to one type, you specify this in the function.

The Kotlin constructor Array () turns out to be more complex: Here you also have to specify the length and a lambda function.

The constructor creates an array with six digits and starts at zero: 0, 1, 2, 3, 4, 5.

You can find out more about constructors and lambdas below in the text.

Each entry in an array is indexed and can be accessed via this index be called. Square brackets are used to indicate the position of the entry in the list.

In this case the function will output "Samuel" because the counting starts with 0.

Operators

As is known from many other programming languages, Kotlin also works with various operators that you can incorporate into your source code. This includes mathematical operators (+, -, *, /, %), Comparison operators (<, >, <=, >=, ==, !=) and logical operators (&&, ||, !). Closely related to the operators are so-called Keywords: Terms that have a fixed meaning in Kotlin and cannot be reinterpreted.

Ranges

In Kotlin, a range describes a type that extends from a certain point to another. The operator is used to generate a range .. or uses the functions rangeTo () or. downTo (). The variant with two dots in a row can count up. With the two functions, however, you define in one direction.

In these simple versions you create a range with steps of one. To the Step size adapt, use the step-Function.

Around address individual data in the range, use this in-Operator. For example, you can create a query or a loop. The operator is used to check whether a value is not part of the range !in.

You can find out more about functions (fun), loops (for) and conditions (if) below in the text.

Functions

Kotlin functions will always be with the command fun created. Then you define the name of the function, which arguments it contains and finally what it does.

We first define the function div (for division) with two int parameters a and b. The function should give us the result of dividing a by b, also in the form of an int variable. In the Main-Function finally we call the previously defined function, pass it concrete values ​​and let the result through println Display (print line) in the console. Kotlin leads the contents of Main() automatically off. This function represents the entry point into a Kotlin program.

Outside of functions, Kotlin does not accept commands. Only declarations are allowed there.

In Kotlin, functions that comprise only one line of code can be represent simplified. Instead of opening curly brackets, writing a new, inserted line and closing the bracket again, an equal sign is used. In addition, the command return waived.

To avoid errors due to missing parameters, you can specify default values ​​when defining the function. If you leave the corresponding parameters free when calling the function, the Default values for use.

Lambdas

A lambda function (or anonymous function) is a function that does not belong to any class or object. Become lambdas housed directly in other functions or variables. You can call them up without the keyword fun to use. In principle, lambdas can be like variables of the type val use and are also created in this way.

Lambda expressions in Kotlin must always be enclosed in curly brackets. Lambdas can also process function arguments. These are through one arrow that separates the parameters from the core of the expression.

Classes

Just like in Java, there are classes in Kotlin Collections of data and functions. To define a class, you simply put the keyword class a. You can then fill the new class with information.

In Kotlin, the constructor is a function that you need to create objects. Therefor knows the programming language Primary and Secondary Constructors. Primary constructors are a convenient shorthand notation, while secondary constructors are similar to the notation used in many other object-oriented languages, including Java. You can see this second variant in the example above.

But there is also the option of leaving out the secondary constructor and using a primary constructor instead. You write this directly in the header of the class and include the parameters of the class. This significantly reduces the number of lines of code.

If you do not want to provide any additional information with regard to the visibility of the class (public, private, protected), you can do without the keyword at all.

All three code examples produce the same result.

You can now use this class in your other source code and feed it with concrete values.

As is common in most object-oriented languages, you can access the properties and methods of an object directly by adding a period and the name of the property or method after the object's.

A specialty in Kotlin is the Data class This type of class is intended to only store data. In principle, one line of code is sufficient for this.

This class can be used directly.

Objects

In Kotlin, objects are instances that can only be defined once (singleton). you usually contain variables and functions. You create an object - similar to a class - in principle with just one line of code. But then the object is empty. You give content to the object in its body.

Loops

There are three different types of loops available in Kotlin: while, do..while and for. These behave like their equivalents in other programming languages. A while-Loop runs until a specified condition occurs.

 

The do..while-Loop behaves very similarly to the variant with while. The difference is that the content of the loop is run through at least once, since the check only takes place at the end.

The for-Loop runs as long as a condition remains true.

Conditions

Kotlin knows three different ways to implement conditional statements or branches: if, if..else and when. The query if lets the computer do a task if the condition is met.

With else add an action to be taken if the condition is not met.

The expression when Finally, there is a special feature of Kotlin: Different actions are carried out depending on different states. This is similar to the when-Expression of what is in other programming languages switch solves; but he works more precisely.

In the body of when accommodate the different verification cases. These are always related to a defined variable.

However, the argument can also be sent directly to when and then does not have to be mentioned again in the body every time. In addition, can a single condition can also trigger multiple actions. To do this, create a new body with curly brackets. We will help you to rule out unexpected cases else.

Nullability

A big annoyance factor when programming with Java is that error NullPointerException. This occurs when referring to an object, its value zero is. Kotlin gets around this problem by not even allowing variables to take the value zero accept. If the case occurs, the message appears during compilation: "Null cannot be a value of a non-null type string" - or a corresponding other warning.

But now there are moments when you want it zero- Consciously use value. For this Kotlin uses the Safe Call Operator: ?.

Hereby you explicitly allow Kotlin that zero is acceptable. The program will then zero output. However, if you want to address a certain property of the variable, you have to use the Safe Call Operator again.

This code will also be used again zero produce, but no error - the program runs. It is a little more elegant if you specify an alternative value. For this you use the so-called Elvis operator: ?: - so named because you can read the string as a smiley with a quiff.

In this example, notes are displayed when a variable has the value zero accepts.

Similar articles

The most popular JavaScript frameworks and libraries

Anyone who has ever worked with JavaScript on a website knows the complexity of the so-called Document Object Model (DOM). JavaScript frameworks and libraries promise easier operation: With a collection of useful functions and simplifications, they help developers. But which are the best JavaScript libraries and frameworks? And in what ...

Spring - the framework for complex Java applications

Java does not play a major role in simple web development, although the programming language certainly has its charm. The language, which was once supported by browsers, has established itself as an efficient solution, especially in the design of backends for business applications. The Spring framework contains various modules that serve as the basis for complex web and desktop applications and that ...

Continuous integration: the continuous integration explained

Recurring annoyance when developing software: the big integration phase at the end - including tedious troubleshooting. The Countiuous Integration way of working eliminates this arduous process - through granular, continuous integration. Each new function is inserted directly into the code base - this sometimes happens several times a day. The team is always on ...

RabbitMQ: Fast messaging

In many situations, applications have to communicate with one another - in a controlled and swift manner. RabbitMQ acts as an intermediary between two services and ensures the smooth distribution of messages. The two programs can even speak different programming languages: no problem for the messaging broker.

Spring Boot Tutorial: Building Java Apps with Spring Boot

Spring has been one of the most popular Java frameworks for years. In combination with the addition Spring Boot, it provides developers with an excellent and easy-to-use basic framework for applications of all kinds. In this Spring Boot tutorial in German, we highlight the requirements for installing and using the framework and show you the first steps towards your own app ....