
Recently, JetBrains, after five years of work,
released the first release of the
Kotlin language. Let's see what kind of language it is, let's try to figure out why and for whom it is, which features it has. Most likely, the article was filled with personal impressions of the language, but I tried not to affect the presentation of useful information. If you still know little or nothing about Kotlin, then I envy you, because in my feeling you can read about the instrument that you have been waiting for a long time, akin to unpacking a New Year's gift. But judge for yourself.
')
What is Kotlin
Kotlin is a small island in the Gulf of Finland near St. Petersburg. Apparently, thus the creators give a reference to the fact that the new language, like the island of Kotlin, is the younger Russian brother of the distant island of
Java .
Who is this language for?
Indeed, the new language is compiled into JVM bytecode (there is also a compilation in JavaScript, but since the release of the compiler is in the JVM, this topic will have to be postponed again). And this means that it can interest everyone who deals with a Java-machine and, in general, languages ​​with a garbage collector (and with the release of the compilation in JavaScript, the coverage and possibilities will be even wider).
Simple and compatible
The two main features of Kotlin, in my opinion, are its simplicity and full compatibility with Java. Kotlin was created by a company that makes a lot of products in Java and which is well versed in modern development tools. A request for a new language has been in the air for a long time, but to make such a language that would allow us to take a (huge) ready-made Java codebase, ordinary Java developers, give them a new tool and seamlessly (but more efficiently) continue development - such a tool until Kotlin did not exist. The creators of the new language, in my opinion, felt very well the needs of business and developers: business was given the opportunity to increase the efficiency of developers, and developers were given a modern development tool. And when I talk about the “modern tool”, I, of course, mean not only the compiler, but also support in the IDE, without which personally my developer’s activities seem to me completely unthinkable.
Bottom line: simplicity allows almost any Java developer to use a language who is willing to spend half an hour looking at a tutorial or language specification, while backward compatibility allows you to use a language in an existing project.
Production-ready
Of course, first of all, JetBrains itself had a request for this language, hence some understanding of how it should be. Moreover, JetBrains also tested it inside the company: by the time this release was released, the company already has at least one
major product made purely on cotlin (yes, I understand that the platform is still written in Java). From this we can assume that statements about the readiness of the language for production are not unsubstantiated. And from my own experience of using a cauldron from 2012, I can say that of the problems that I encountered in pre-release times, none of them survived to release. There are still minor problems with the plugin for IDEA, but the compiler itself works like a clock.
Compatible with Java 1.6
This is a very important point, because it is this version of Java that is used in all modern versions of Android, and, in spite of the
planned transition to OpenJDK , the eighth version falls into the hands of developers for mobile devices not as soon as we would like. Of course, there are all sorts of retro-yambda and other tricks, but Kotlin is not only lambda for android, but also modern language, which allows to make development for android
easier and more enjoyable at no extra cost. And the increase in the size of apk is not significant at all in modern times: 823KB (for version 1.0.0)
Special features
Of course, it’s better to search the full list of possibilities in the
documentation , but I will try to reflect the most important points in my opinion in general terms:
Null safety
For some reason, historically,
this feature of the cotlin is remembered first. And although it is certainly important, in my opinion is not the most important. Here, the language allows defining variables, fields, constants, etc., to indicate whether they can hold a reference to null. Raises the idea of ​​annotations like @Nullable and
NotNull to a new level, allows you to intelligently lead to a non-nullable type after checking it for null. It should be noted that there are cases when this feature is at odds with my ossified Java development about how certain things should be done, but after some thought a good solution is always found.
fun someFunction(someNullableParam:SomeType?) { if(someNullableParam != null) {
Type inference
Yes, Kotlin almost everywhere where possible, knows how to deduce the type, but the type will still have to be defined for public methods and properties, which is very reasonable (I am told that this is not true - it was removed from some version):
Extension methods
A feature that I’m badly lacking in Java to increase the flexibility of language and solutions. It is possible to define a method for a type separately from its (type) declaration. Such a function, of course, will not be virtual and in no way changes the class to which we add the method, however, it allows you to add both utilitarian functionality for the already existing code and unload the interface from the same utilitarian methods.
interface Vector2 { val x:Float // , (property) val y:Float // Java getX() getY() } val Vector2.length:Float get() = (x * x + y * y).sqrt() // , extension- Float operator fun Vector2.plus(other:Vector2):Vector2 = createVector(x+this.x, y+this.y) // - fun Vector2.dot(x: Float, y: Float): Float = x * this.x + y * this.y infix fun Vector2.dot(vec2: Vector2): Float = dot(vec2.x, vec2.y) fun usage(vec1:Vector2, vec2:Vector2) { val dotProduct = vec1 dot vec2 val sum = vec1 + vec2 // val length = sum.length // }
Lambda
Of course, like any modern language with a claim to the possibility of functional programming, in Kotlin, function is the essence of first class, if translated literally. Those. you can not only declare functions directly in the package (from the java they are still visible in the classes by the file name), but also passed as parameters, returned from other functions, and so on. And now, of course, no one will be surprised by this, but for example in comparison with Java, where there are no syntactically functions as such (but only functional interfaces), in Cotlin there is a full-fledged syntax for declaring a function:
fun passTen(func: (Int)->Int ): ()->Int { return { func(10) } }
Lambda extension
Along with extension-methods, this is another my favorite feature. Allows you to define a lambda, which will also be an extension-method. It does not sound very much, yes. Let's look at an example:
class World(val name:String = "world") val printName:World.()->Unit = {
This feature looks especially interesting in
builders , which I suggest you look at yourself - in case you are wondering how such constructions are made:
html { head { title {+"XML encoding with Kotlin"} } body { h1 {+"XML encoding with Kotlin"} a(href = "http://kotlinlang.org") {+"Kotlin"} } }
Inline-functions
Marking a function as inline, we ask the compiler to place it at the place of use. Most often, such things are done by runtime, but there are cases when we know for sure that the function is just a shortcut for some action - it works especially effectively with the transmitted lambdas:
inline fun lock(lock:Lock, block:()->Unit) { lock.lock() try { block() } finally { lock.unlock() } } fun usage() { lock(Lock()) {
Of course, a series of restrictions is imposed on such functions; for more details, see the
documentation .
Delegation
In the cotlin there are two types of delegation.
The first , which allows you to delegate all the methods of the implemented interface to an instance of this type:
interface Connection { fun connect() } class ConnectionWrapper(val connection:Connection) : Connection by connection
This syntax has a number of limitations. For example, an instance for delegation must be known before the constructor is called.
The second type of delegation is
delegated properties . Allows you to define an object with get (and set for var) methods to which access will be delegated when accessing an object property.
class Foo { private val someProeprty by lazy { HavyType() } }
Generics
The creators of Cotlin have somewhat
improved Java generics. Due to compatibility with Java, not everything worked out as we would like, but they managed to fix many unpleasant moments that their predecessors did not take into account when working on Java 5.
Destructuring
val (first, second) = someFunc()
For this code to work, the return value from someFunc () must be of the type that has (extension) the methods component1 (), component2 ():
class Foo { fun component1():String = "test" fun component2():Int = 10 } fun someFunc():Foo = Foo()
Data Classes
Sugar compiler to create beans:
data class Bean(val a:String, val b:Int)
Creates a bin with fields + autogenerates equals + hashCode + toString () + componentN from the section above, which allows you to write such code:
fun someFunc():Bean = Bean("test", 10) val (a, b) = someFunc()
A useful thing, but about the nuances, see the item "On the sad."
Standard library
Of course, not to mention the
standard library . Since Kotlin is primarily aimed at working with Java, it does not have its entire standard library. Most of the Kotlin standard library is aimed at improving and correcting the older brother’s library, Java. However, this is a topic for another great article.
About sad
You might think that this is a perfect product, but no, there are some unpleasant moments:
IDE
Above the plug-in is still working and working, occasionally gives out exceptions, is poorly able to toString () in debug, and also likes to miss a link to the source, sometimes (apparently due to the inline features) confuses where the pointpoint is posed and the like. All this of course will eventually be corrected with time, but now we have exactly that.
Data Classes
Admittedly, the idea was good, but at the moment there are a lot of
restrictions imposed on this type of classes, which allows them to be used in a much more limited number of cases than we would like. The creators of the language promise to work on solving this problem, but so far.
Some untidiness
Of course, carelessness is primarily in the minds, but the shortness of the syntax sometimes plays a cruel joke, and in some places the code looks unimportant. Perhaps the presence of a style guide would fix this problem somewhat, but for the time being it is sometimes necessary to try to not only work well, but also look beautiful. Especially in my subjective opinion scary look get, set for properties.
Finally
One article cannot cover all the features and aspects of the language, but I did not try. My task was to introduce the language, maybe pay attention to it. Anyone who is interested can find more in the
documentation , see the
source ,
try ,
ask a question . It is difficult to predict the popularity of this language, but it is already clear that many have waited for such a product, projects on Kotlin appear like mushrooms, and after the release the frequency of their appearance will increase. In my impression, the language is well balanced and thought out - while writing code, it seems that everything is in its place. If you use jvm or any other language with garbage collection, it makes sense to pay attention to Kotlin. For me personally, cotlin is the tool I have been waiting for a long time and now I can’t imagine how I could do without it.