Kotlin is a relatively new, statically typed, JVM programming language developed by JetBrains. Version 1.0 was released in early 2016. Nevertheless, Kotlin has been available for a long time and was used productively even before this release. Especially in the Android community, Kotlin has been able to gain some followers and has been on everyone’s lips ever since last year’s Google conference “I / O”, when it was declared that Kotlin is now the official “android development language”. We at n-design are always looking forward to new frameworks and programming languages so that this development will be followed with interest.
WHY IS KOTLIN SO INTERESTING FOR ANDROID?
The reason is relatively simple because Kotlin can be compiled to Java 1.6 bytecode. Android does not support the latest version of JDK 1.8 in most versions, allowing Android developers to rely on advanced Java language features such as lambdas and streams have to give up. Kotlin, of course, also offers these features, and many others, although only Java 6 is needed to run the compiled code. JetBrains’ idea in developing the language was to create an alternative to Java that fixes problems, increases productivity and continues to interact fully with Java code. I think any Java developer who has worked with JVM languages like Groovy and Scala knows that Java is often very “talkative” and a lot of boilerplate code needs to be written, even to do simple things. Kotlin starts here and allows the writing of much shorter source code, where Scala was clearly used as inspiration.
KOTLIN SYNTAX
Here are some examples to demonstrate how Kotlin source code feels:
TYPE INFERENCE OF LOCAL VARIABLES
The following lines show how variables are declared in Kotlin:
var myvar1 = 100
var myvar2 = "text"
The types of myvar1and myvar2( Intor String) are automatically determined by the compiler so they do not have to be specified explicitly.
TIP: The two variables can be assigned a different value as often as desired. If you want to use final variables, use val instead of var. The individual lines do not have to be; scheduled.
DATA CLASS
If you think about how to develop a POJO Person in Java that has properties like name, ageand job, of course, appropriate implementations for toString(), hashCode()and equals(), as well as the necessary getters and setters, you immediately have a relatively large file in mind very often recurring principle corresponds.
POJO IN KOTLIN
data class Person(val name: String, val age: Int, val job: String)
In Kotlin it looks different — this line produces all the code you want.
ZERO SECURITY
We all fear NullpointerExceptions. These mostly occur due to programming errors, because it was not clear that certain values could be at runtime null.
Kotlin tries to eliminate this source of error by distinguishing between those variable types that are nullable and those that are not. This is clarified by the syntax. As you can imagine, variable types that cannot reference are the default. Illustratively, this means, for example, that a variable of the type can Stringnever be nullincluded. The corresponding type of nullable string is declared as.
This alone would not make a big difference, so when using nullable types, there are a few things to consider:
EXAMPLE: WORKING WITH NULLABLE STRING
val iCanBeNull:String? = null
//...do some hard work with the string...
iCanBeNull?.length
The last line of code will be the length of the Strings, if iCanBeNullnotnull referenced, ornull in the other case. That is, the call lengthwill not operate on a null pointer and thus NullpointerExceptions are impossible.
It has to be mentioned that the language certainly leaves open the possibility to force such calls and to accept them. But should you really do that ?!
STRING TEMPLATES
A feature that everyone quickly understands and asks why Java does not offer it:
USE VARIABLES AND EXPRESSIONS DIRECTLY IN STRINGS WITHOUT EXPLICIT CONCATENATION
var insertMe = "Reader"
println("Hello $insertMe") //Prints >>Hello Reader<< on Console
println("Hello ${insertMe.toUpperCase()}") //Prints >>Hello READER<< on Console
METHODS: DEFAULT VALUE FOR PARAMETERS AND NAMED ARGUMENTS
In Java, it is often necessary to overload a method multiple times to provide different API variants, for example, if one of the parameters does not necessarily have to be specified. The method then exists with and without this parameter. A much more readable alternative is possible in Kotlin:
DEFAULT VALUES
fun myMethod(notOptional: String, optional: String = "defaultValForOptionalString"){
println("myMethod called with $notOptional and $optional")
}
//Possible Calls
myMethod("arg1", "arg2")
myMethod("arg1")
As you can see, a default value is defined for the second parameter so that a call with only the first parameter is valid. It is also possible to write the names of the parameters to the arguments when calling a method:
NAMED ARGUMENTS
//You choose your own arg sequence
myMethod(notOptional = "arg1", optional = "arg2")
myMethod(optional = "arg2", notOptional = "arg1")
LAMBDAS
Kotlin has, unlike Java, appropriate function types. Since Java 1.8 is, as we know, is possible with lambdas and streams begin to be able to program functional. However, one has to keep in mind that the implementation of this is a bit unusual when you are familiar with functional programming languages. The problem is that Java does not know a function type; Functions are not a First-Class Citizen within the language. Instead, a lambda is an implementation of a SAM type.
In Kotlin, a function is assigned a higher priority. There is a function type that looks like this, for example: (Int, Int) → Int(A two- Intparameter method that Intreturns one).
ANONYMOUS METHOD AS LAMBDA
val multiply = { x: Int, y: Int -> x * y } //Typ: (Int, Int) -> Int
val res = multiply(3,5)
A method can simply be assigned to a variable and used at the next opportunity. Of course, methods can also be passed as parameters. As a syntactical highlight one has considered here that it
it is not necessary to specify parentheses if a lambda is the only argument of the method.
it is not necessary to name the method parameter if it is the only parameter. The implied name is then “it”.
it is not necessary to use method parameters at all. These can be named “_”.
These cases are shown below:
LAMBDA SYNTACTIC SUGAR
val ints = 1..4
//a) & b) filter() has only one parameter of type Int -> Boolean
ints.filter { it > 0 }
val map = mapOf(Pair(1,"val1"),Pair(2, "val2"))
//c) Key of Map-Entry is not used!
map.forEach { _, value -> println("$value!") }
Finally, an example that demonstrates all the beauty and, I think, readability:
LAMBDA EXAMPLE
//Determine Names of all Males in people-collection
val namesOfMaleMembers = people.filter { it.gender == Person.Sex.MALE }
.map { it.name }
ADDITIONAL
The examples are only a small part of the many great features that Kotlin offers and you would like to enjoy in Java. I have been working with Kotlin for some time and have become a big fan and supporter. The entry into the language can succeed very quickly, unlike me personally at Scala was the case.
TIP: Some of the language constructs presented above are also desired in a similar way in the long list of “JDK Enhancement Proposals” (JPE), eg JEP 286: Local-Variable Type Inference, described by Brian Goetz, describes the type inference of local variables. Maybe a part of Java 10?
ARE THERE WORTH CONSIDERING FEATURES IN KOTLIN?
I think this question can be answered in principle with no. However, Kotlin allows certain freedoms that should be used wisely. For example, Kotlin allows defining functions and variables in files that are not associated with a class, as would always be the case in Java. These can be referenced unqualified at any point. A useful application is static utility methods (eg Collections). The question is: who is allowed to define such things within the project? In my opinion, you should discuss within the project how to deal with such things and at best define a central position.
The same applies to “extension functions”: these are in principle methods that are added to a class from the outside. For example, one could Stringextend the class using any methods, although it is actually finaland could not be extended by inheritance. Strictly speaking, this is the absolutely right approach, according to the open/closed principle, which is thereby enforced. For the caller is unfortunately not directly visible whether a member function or an artificial extension is called. However, it is also true here that an import is necessary, whereby the criticism is somewhat mitigated. In my opinion, this too is a cautious feature. Similar to top-level functions, it should be clear where such functions should be defined.
IS KOTLIN A SERIOUS ALTERNATIVE TO JAVA?
In my opinion, Kotlin is currently the JVM language that can seriously compete with Java. Kotlin makes it possible to create applications for the JVM, Android, the browser, and soon even the native kind. Recent events in connection with Google and the announcement that next to Java Kotlin now officially can be used for the programming of Android kotlin apps have the potential to trigger a hype and make the language more familiar. Many companies already use Kotlin productively, creating a community, and the first conference is planned for this year. Unlike many other JVM languages, Kotlin has the great advantage of being 100% interoperable with Java. Specifically, this means that the many available Java libraries and frameworks can be easily used and existing code bases do not have to be completely migrated.
1. Best known for their IDEs, especially IntelliJ IDEA.
2. see also an introduction to the Java 8 features
3. An interface with exactly one abstract method.
4. A package-level import is still necessary.
5. Unlike Java, classes in Kotlin are by default final, according to “Effective Java, Item 17: Design and document for inheritance or else prohibit it.”
So, will java in android development will be extinct or JAVA will make a comeback with their new version only time will tell.