In which year, Kotlin programming language appeared. About Kotlin language for Java programmers. Basic elements of language

Official language for developing on Android.

Why did Kotlin named in honor of the island in the Finnish bay, as and when the language became popular among mobile application developers, why can it be convenient for use and why did they originate? Marketing Manager Kotlin Roman Belov told "Paper"As in St. Petersburg, they created a language recognized by Google.

Photo from the archive of Roman Belova

How and when did the Kotlin programming language appear?

We started to develop Kotlin in 2010. By that time, Jetbrains had already had ten years and the main product of the company - Jetbrains Intellij Idea, fully written in Java, was already very large. It became clear that in many respects Java does not suit us. There were several alternative programming languages, but it turned out that none of them correspond to the requirements that we put forward to the language that would like to go.

There was a second reason. When a lot of people are going to in one place with great expert experience in the field of programming languages, it often turns out that a new language is born. So it turned out. First, there was a conscious and serious need, and secondly, we could satisfy it.

Like many of our products, we created Kotlin based on their need. This, in general, the principle in the development of the company: we see that there is no tool on the market, which would solve some problem, and then create it. Our first users are always ourselves. Therefore, we usually get very practical and pragmatic tools.

Why is Kotlin called this way?

At that moment, when the name was invented, on JVM (Java Virtual Machine - approx. "Paper") There were still languages \u200b\u200bcalled in honor of the islands: Java, Ceylon. And we thought: what is the island near us? Kotlin. And this name has taken place. There is no tradition or rule here, but it happened, there is no deeper thoughts for this.

What are the features of the language?

Probably the most successful word that comes up to the Kotlin language is pragmatic. Languages \u200b\u200bare different: some come out of the academic environment, others are designed for specific platforms. We were originally aimed at a practical language for the widest possible audience. He had to be democratic, that is, without dull things. There are situations where the programmer knows all the subtleties of the language and thanks to this he writes a tricky code, - and in this code none of the junior programmers can climb. We need a language that is equally good for both novice programmers and advanced.

Inside the company, we also have full democracy: each programmer itself decides, in what language to write, on Java or to Kotlin, and not everything goes to Kotlin. For me, as for the marketing manager, the language of JetBrains is a small world. When everything will go to Kotlin in our big company, then, probably, all over the world programmers will move to it. But, indeed, the percentage of the use of Kotlin in the company is consistently growing.

What is Kotlin so good? First of all, the developers love Kotlin for its brevity and expressiveness. It is characteristic of all new languages. Previously, people were not very embarrassed, then the size of the programs became more - people realized that they write a lot of completely meaningless pieces of code just because it requires the syntax of programming language.

The second reason is that it is fully compatible with Java and allows you to gradually migrate from Java applications to the Kotlin application. For example, the Basecamp application has completely migrated with Java on Kotlin.

The third item - Kotlin is safe: the semantics of the language laid the principles that prevent a number of very common mistakes that usually happen at the time of the program execution. This allows you to write a safer code that ultimately helps save money and reduce testing costs.

How did Kotlin notice application developers?

In jetbrains we do not engage in Android-development and originally no one thought that Kotlin would be a language that is so successfully suitable for the purposes of Android developers. But at some point it turned out that Android was stuck on Java 6 and very many new Java features on Android are not available. Then progressive developers paid attention to Kotlin.

We realized that Kotlin could be very useful for Android, and began to refine the features that help Android developers, took into account their needs when developing a language design.

A year ago, we had a fairly big event: the grade assembly system, with which all applications are collected for Android, announced the transition to Kotlin.

In a sense, the story with Kotlin on Android is completely fabulous and housing: we just made the programming language, and he really liked developers. This is a story about motion from the bottom up, and not the opposite. The developers have long requested Google to support Kotlin. And Google listened to them.

With the announcement from Google formally nothing changes for us: we continue to develop a language and are aimed at different platforms. Naturally, we anticipate particular attention to the language from Android developers: it will, in particular, expressed in error messages, in queries to support one or another functionality, and, of course, we will all process it all. But in general, of course, we will continue to move along the intended path.

Who and why use Kotlin language?

In the company, we began to apply Kotlin years since the 2012, but the official release of the language was February 17, 2016. Prior to that time, the design of the language was actively changing and supported on Kotlin was quite problematic. It should be understood that the development of programming languages \u200b\u200brequires much attention to backward compatibility. And when we declared a release, referred to backward compatibility: for the fact that the new code will be compatible at the binary level with the old. And we carry out these obligations.

Now Kotlin language in its applications use such Russian companies as Avito and Rocket Bank. Over the past year, Kotlin tried 160 thousand programmers. Until today, Kotlin showed an exponential growth in the number of programmers, and I think, Google's announcement will help us continue this growth.

Fun Main (Args: Array ) (Val Numbers \u003d ArrayListof (15, -5, 11, -39) Val nonnegativenumbers \u003d Numbers.Filter (IT\u003e \u003d 0) PrintLN (NonnegativeUnumbers)) // Conclusion: 15, 11

Higher order functions are functions that take other functions as arguments and return functions. Consider the following example:

Fun Alphanum (FUNC: () -\u003e Unit) ()

In it, FUNC is the name of the argument, A () -\u003e Unit is the type of function. We say that FUNC will be a function that does not accept arguments and not returning anything.

Lambda expressions, or anonymous functions are functions that are not declared, but are transmitted as expressions. Here is an example:

Val Sum: (int, int) -\u003e int \u003d (x, y -\u003e x + y)

We declare the SUM variable, which takes two numbers, folds them and takes the value of the amount given to the whole. To call a simple sum (2.2).

Comparison of speed Java and Kotlin

The first assembly of Kotlin-code takes about 15-20% more time than a similar process on Java. However, the incremental assembly of Kotlin is even a little faster than Java. Thus, the languages \u200b\u200bare about equal in the compilation rate.

Future kotlin.

Kotlin is the next Java development stage with which it is fully compatible. This makes it an excellent tool for mobile and enterprise applications. And since Kotlin is now the official Android language, you can not be afraid that, having studied it, you will stay without work.

In the study of this language, a series of articles will help you describing the process of creating a simple Mobile application Keddit - a client for a popular REDDIT resource. All of her parts for your convenience we listed in the list below.

You will need the following libraries:

  • Retrofit 2.0;
  • RXJAVA;
  • Picasso;
  • RecyclerView;
  • Extensions Kotlin for Android;
  • Dagger 2.

All sources are available on GitHub. The series consists of the following parts.

This article talks about the Kotlin programming language. You will learn about the reasons for the emergence of the project, language capabilities and see some examples. The article is primarily written in the calculation that the reading sign with the Java programming language, however, knowing another language will also be able to obtain an idea of \u200b\u200bthe subject. The article is superficial and does not affect the compilation issues in JavaScript. On the official website of the project you can find complete documentation, I will try to tell about the language in Brief.

about the project

Not so long ago, JetBrains, which is engaged in creating development environments, announced its new product - Kotlin programming language. A wave of criticism collected on the company: criticizing offered companies to drag and finish the plugin for Scala, instead of developing their tongue. The developers on Scala really lacks a good development environment, but also the problems of the plug-in developers can be understood: Scala, which was born thanks to researchers from Switzerland, has absorbed many innovative scientific concepts and approaches that made the creation of a good tool for developing an extremely difficult task . At the moment, the segment of modern languages \u200b\u200bwith static typing for JVM is small, so the decision to create your own language together with the development environment to it looks very far from it. Even if this language does not take place at all in the community - Jetbrains primarily makes it for his needs. These needs can understand any Java programmer: Java, as a language, develops very slowly, new opportunities in the language do not appear (first-order functions We are not waiting for no first year), compatibility with old language versions makes it impossible to appear many useful things in the near Future (for example, decent parametrization of types). For a company that develops on programming language is the main working tool, so the efficiency and simplicity of the language are indicators on which not only the simplicity of the development of tools for it depends, but also the costs of a programmer for coding, i.e. how easy it will be this code to accompany and Wake up in it.

About language

The language is statically typed. But compared with Java, the Kotlin compiler adds to the type of information about the features of the link to contain NULL, which tightens the types of types and makes execution more secure:

Fun Foo (text: String) (text.tolowerCase ()) // NPE? No!) Val str: String? \u003d NULL // String? - type allowing null-s foo (STR) //<- компилятор не пропустит такой вызов -- // тип str должен быть String, чтобы // передать его в foo

Despite the fact that this approach can save a programmer from a number of problems associated with NPE, for a Java programmer at first it seems unnecessary - you have to do extra check or transform. But after some time programming on Kotlin, returning to Java, you feel that you lack this information about the type, you think about using NULLABLE / NOTNULL ANNOTS. With this, there are no backward compatibility issues with Java - there is no java in the Baitcode, but as far as I know, this question is still in the solution process, but for now all the types coming from Java are NULLABLE.

By the way, about backward compatibility: Kotlin is compiled in the JVM bytecode (creators of the language spend a lot of strength to support compatibility), which allows you to use it in one project with Java, and the ability to mutually use the Java classes and Kotlin classes make a completely minimal Kotlin imitation threshold in a large already existing java project. In this regard, it is important to use multiple Java-developments, creating a project entirely on Kotlin. For example, I almost did not work up to make a small project based on Spring-Webmvc.

Let's see the controller fragment:

PATH (Array ("/ Notes /")) Controller Class NotesController (Private Autowired Val NotesService: NotesService? \u003d NULL PATH (Array ("All")) Fun All () \u003d render ("Notes / Notes") Notes ", notusservice !!. all)) // ...)

The features of the use of annotations in Kotlin are visible: it looks not as gentially as in Java (it concerns it particular cases, for example, an array of one element), but annotations can be used as "self-made" keywords like Autowired or Controller (if you set an Alyas Type when imported), and according to the possibilities of annotation approach to these classes.

It should be noted that Spring could not wrap the kotlin-classes for transaction management - I hope in the future it will be possible.

In the language there is support for FIRST-CLASS FUNCTIONS. This means that the function is the built-in type type for which there is a special syntax. Functions can be created on the place, transfer to other functions to the parameters, store links on them:

Fun Dosomething (Thing: () -\u003e Unit) (// declare a function type function // () -\u003e Unit does not accept anything and // Nothing important returns Thing () // Call) Dosomething () (// And here On the fly we create a function of type // () -\u003e unit and transmit it to the doshomething function // if the function is the last parameter, you can // take it out for the PRINTLN call brackets ("Hello World"))

If you add an extension functions to this, allowing you to expand the already existing class by the method that does not violate the encapsulation of the class, but to which you can contact as methods of this class, then we will receive a fairly powerful expansion mechanism of the well-poor in terms of standard Java libraries. By tradition, add the list of list filtering already existing in the standard library:

Fun. List .Filter (Condition: (T) -\u003e Boolean): List (Val Result \u003d List () for (Item in this) (IF (Condition (Item)) Result.add (Item)) RETURN RESULT) VAL SOMELIST \u003d LIST (1, 2, 3, 4) .FILTER (IT\u003e 2) // SOMELIST \u003d \u003d.

Note that the variables do not specify the types - the Kotlin compiler displays them if it is possible and does not interfere with the absorption of the interface. In general, the language is made in such a way as to maximize the person behind the keyboard from the gains of unnecessary signs: a short, but clear syntax with a minimum of keywords, no need for points with a comma to separate expressions, type output, where it is appropriate, the lack of a NEW keyword to create Class - just necessary.

To illustrate the subject of classes and shorts, look at the following code:

// Creating bean classes becomes // Little, fields can be announced // Right in the Class Timelord Designer declaration // Class may not have the body of Class Tardis (Val Owner: Timelord) Fun Main (Args: Array ) (Val Doctor \u003d Timelord ("Doctor") Val Tardis \u003d Tardis (Doctor) PrintLN (TARIS.OWNER.NAME))

In several lines, we were able to declare two classes, create two objects and withdraw the name of the Tardis owner! It can be noted that the class is declared with the parameters of its only possible designer, which are simultaneously the declaration of its properties. Maximum briefly, but at the same time informative. Surely there will be those who condemn the inability to declare more than one constructor, but it seems to me that this has its own pragmatism - after all, several designers in Java or allow you to declare the default parameters that Kotlin supports the language level, or convert one type to another, With which it will work this class, and this can already be quietly to give off the factory method. Pay your attention to the announcement of "variables" and fields. Kotlin makes us make a choice: Val or Var. Where VAL - declares an unchangeable Final-link, and var - a variable than helps to avoid the ubiquitous use of changeable links.

Example

So we got to the place where something more interesting can be done. On the interviews, I often give a task to implement a tree, make it bypass and determine some action with an element. Let's see how it is implemented in Kotlin.

So I would like to look like:

Fun Main (Args: Array ) (// Create a small tree Val Tree \u003d Tree ("root") (Node ("1-1") (Node ("2-1") Node ("2-2")) Node ("1-2" ) (Node ("2-3"))) // Come on and display the values \u200b\u200bin the Tree.TraVERSE console (PrintLN (IT)))

Now let's try to implement it. Create a tree node class:

/ ** * @Param Value node data * / CLASS Node (VAL VALUE: T) (// Children Private Val Children assembly: List \u003e \u003d ArrayList () / ** * The method that creates and adds the child to the node * @param value value for the new node * @Param init function of initialization of the new node, optional * Parameter * / Fun Node (Value: T, Init: Node . () -\u003e Unit \u003d ()): Node (Val Node \u003d Node (Value) node.init () children.add (node) return node) / ** * The method recursively bypass all child nodes starting from the * node itself, the handler is notified about each node * @Param Handler function handler for each node value * / Fun Traverse (Handler: (T) -\u003e Unit) (Handler (Value) Children.Foreach (Child -\u003e Child.Traverse (Handler)))

Now add a function to create a wood vertex:

/ ** * Creates a vertex of wood with the value of Value and initializes its children by the init. * / Fun. Tree (Value: T, Init: Node . () -\u003e Unit): Node (VAL NODE \u003d NODE (VALUE) // Call the Init method, transferred to // Parameter, on the Node.init () Node object object)

In two places of the code, the design of the Node type was used. () -\u003e Unit, its meaning is that the type-function is expected to be executed as an Node type object method. From the body of this feature there is access to other methods of this object, such as the node.node () method, which allows the initialization of the tree similar to that described in the example.

Instead of imprisonment

At the expense of good compatibility with Java and the ability to replace the old code gradually, in the future, Kotlin could be a good replacement of Java in large projects and a convenient tool for creating small projects with the prospect of their development. The simplicity of the language and its flexibility gives the developer more opportunities for writing a quick, but high-quality code.

If you are interested in the language, all the information about the language can be found on the official website of the project, the silicones on the GitHub-E, and the errors found in Issue Tracker found. There are still many problems, but the developers of the language are actively struggling with them. Now the team is working on the yet not very stable version of Milestone 3, after stabilization, as far as I know, it is planned to use a language within the company Jetbrains, after which the first release is already planned.

Tags:

  • kotlin.
  • java.
  • jetbrains.
Add Tags

05/18/2017, Thu, 14:39, MSK Text: Alexander Kornev

Google developers made Kotlin the first class language for the Android OS, noting that it will not yet be replaced by the main "first-class" language Java.

Kotlin as the first class language for Android

On Thursday at the Annual Google I / O conference, the developers reported that the Kotlin language created by Russian programmers will become the "first class language" to write applications for Android. As TechCrunch writes, Google also told about the organization together with the Creators of the Language - Jetbrains - Special Fund for the Development of Kotlin.

Google stressed that Kotlin will be an additional language and in no case will not replace Java and C ++ (today the language of the first class for Android is Java). It is planned that the Kotlin tools based on JetBrains IDE will be included in Android Studio 3.0 - the official development tool for Android OS.

"Since Kotlin is fully supported by Java, you used to write applications on it, but now it will be supported by the authority and reputation of Google," say journalists.

Google translates Android to Kotlin tongue created in Russia

At the same time, Google does not become the owner of Kotlin. The rights will still belong to jetbrains. The language will continue to work with other platforms, for example, as a native code for iOS and Mac or to compile the JavaScript code for web applications.

In a competitive fight with SWIFT

Kotlin is a statically typed programming language running over JVM compiling JavaScript. Language is developed since 2010, its source code was opened in 2012 its name Kotlin received in honor of the island of Kotlin in the Finnish bay, on which Kronstadt is located.

Recall, in the spring of 2016 in Google about the prospect of developing applications for Android SWIFT - programming language for iPhone and iPad. And at the same time, Kotlin was named as a possible alternative language. At first, SWIFT was an internal project of Apple, but later its source code was opened by developers.

It was reported that the possible reason for the search for a replacement for Java could be the problem of a legal plan with Oracle Corporation, which insists that Google violated its copyright and patents. Experts noted that to adapt SWIFT to Android would require the development of a new execution environment for the mobile OS, adaptation of the standard library, providing language support in programming interfaces (API) and developer tools, etc.

From Kotlin, SWIFT is different, according to experts, higher productivity. Among the advantages of Kotlin has already mentioned full compatibility with JavaScript.

In recent years, there has been a new language need compiled into a portable byte code for the Java virtual machine. There are several projects to create such languages \u200b\u200band one of them - Kotlin, a statically typed object-oriented language.

11/07/2011 Andrey Breslav

In recent years, there has been a new language need compiled into a portable byte code for the Java virtual machine. There are several projects to create such languages, one of which is KOTLIN, a statically typed object-oriented language compatible with Java and intended for industrial application development.

The history of the development of "alternative" languages \u200b\u200bon the Java platform has more than decades, but dissemination such languages \u200b\u200breceived only relatively recently. On the wave of popularity of dynamically typed languages, Jruby, Groovy and Clojure rose, and among statically typed languages, SCAAL, Fantom and Gosu should be mentioned. The Java language itself is also not in place, but its development is complicated as the need to maintain backward compatibility and the difficult fate of Sun Microsystems, absorbed by Oracle.

Against this background, a new Jetbrains project under the code name Kotlin (emphasis on "O"), on the one hand, looks almost tribute to fashion, and on the other, it is surrounded by a noticeable number of competitors. However, we feel confident enough in this situation, and there are several reasons for that. First, JetBrains has been engaged in integrated development media for different programming languages \u200b\u200b(many of which work on the Java platform), and during this time a strong team of specialists was collected and a significant experience in programming languages \u200b\u200band related technologies has been accumulated. Secondly, we cannot say that any of the existing languages \u200b\u200bon the Java platform fully satisfies our needs, and we believe, based on preliminary reviews of programmers of the whole world, that our colleagues in other companies are experiencing similar difficulties.

The development of the Kotlin project began in the summer of 2010, in July 2011 the project was officially announced and a description of the language was posted on the site. The release of the public beta version of the compiler is scheduled at the beginning of 2012.

Creating a language, we were guided by a number of requirements that seem most important to such a project.

Compatibility with java.Java platform is primarily ecosystem: In addition to the "official" products of Oracle, it includes many open source projects: libraries and frameworks of a different profile, on the basis of which a huge number of applications are built. Therefore, compatibility with the existing code, which is written in Java is very important for the language compiled for this platform. It is necessary that existing projects can go to a new language gradually, that is, not only the code on Kotlin should easily call the code on Java, but on the contrary.

Static guarantees of correctness.During the compilation of the code on a statically typed language, there are many checks designed to ensure that certain errors will not occur during execution. For example, the Java compiler ensures that objects on which certain methods are "able" to perform them, that is, that in the appropriate classes these methods are implemented. Unfortunately, besides this very important property, Java does not guarantee anything. This means that successfully compiled programs are completed with execution time errors (cause exclusive situations). A bright example is to make the zero reference, in which the exception of the type NullPointerexception is caused during execution. An important requirement for a new language is the strengthening of static guarantees. This will allow you to detect more errors at the compilation stage and, thus, reduce test costs.

Compilation rate.Static checks simplify programming, but slow down the compilation, and here it is necessary to achieve a certain balance. The experience of creating languages \u200b\u200bwith a powerful type system (the most striking example is Scala) shows that such a balance is not easy to find: compilation often becomes unacceptable long. In general, such a characteristic of the language, as the project compilation time, may seem secondary, however, in the conditions of industrial design, when the volume of the compiled code is very high, it turns out that this factor is very important - after all, the code is compiled, the programmer often cannot continue to work. In particular, a quick compilation is one of the important advantages of Java compared to C ++, and Kotlin should save this advantage.

Laconicity.It is known that programmers often spend more time reading code than on his writing, therefore it is important that the designs available in the programming language allow you to write programs briefly and understandable. Java is considered a verbose language (Ceremony Language - Ceremonial Language), and the Kotlin task is to improve the situation in this sense. Unfortunately, strict methods for evaluating languages \u200b\u200bin terms of their conciseness are quite weak, but there are indirect criteria; One of them is the ability to create libraries, working with which is close to use subject-oriented languages (Domain-Specific Language, DSL). To create such libraries, a certain flexibility of syntax is required to combine designs of higher orders; The most common functions of higher orders, that is, features that take other functions as parameters.

Availability to explore.Sophisticated static checks, flexible syntax and higher order designs complicate language and make it difficult to study, so it is necessary to limit the set of supported capabilities to a certain extent to a certain extent that the language is available for study. When developing Kotlin, Scala's experience and other modern languages \u200b\u200bwas taken into account, and too complicated concepts were not included in the tongue.

Instrumental support.Modern programmers actively use various automated tools, the central place among which occupy integrated development environments INTEGRATED DEVELOPMENT ENVIRONMENT, IDE). The ten-year experience accumulated in Jetbrains shows that certain properties of the language can significantly impede instrumental support. When developing Kotlin, we consider this fact and create IDE at the same time with compiler.

Basic elements of language

Functions. Kotlin is an object-oriented language, but, in contrast to Java, it allows you to declare functions outside the classes. In Java, static methods are used for these purposes, which leads to classes, actual not as those: their instances are never created, but only static methods are caused.

Ads in Kotlin are combined in space names (NameSpace), and the function can be announced directly inside the namespace:

namespace.example ( fun.mAX (A: INT, B: INT): int ( if(A Returna. return.b))

An ad function is preceded by a key word fun., Types of parameters are indicated after the colon following the parameter name. Similarly denotes the type of return value of the function. Such a syntax follows the traditions of the "functional world" languages, such as ML and SCALA. It makes it easy to lower typical annotations if the type can be removed Compactor from context automatically.

Variables In Kotlin, as in Scala, is announced using keywords val.(unchangeable variables) and var.(changeable):

var.sinsum: Double \u003d 0.0 for(x in xs.) { Val.y \u003d sin (x) sinsum + \u003d y)

In this example, the type of unchanged variable y is omitted, since the compiler can display it automatically by the value of the right part of the variable definition. The type of variable variable Sinsum is clearly indicated only in order to demonstrate the corresponding syntax; Compiler is enough information to display the type and in this case.

Classes.The main tool for decomposition in Kotlin, as in other object-oriented languages, are classes. When class declaration, the design of the constructor parameters is indicated directly in the title:

classINTPAIR (X: INT, Y: INT) (...)

Class instances are created by direct constructor call; Keywords newin Kotlin no:

val.xy \u003d intpair (x, y)

The class header also indicates the list typical parameters (Generic) in angular brackets and list of supels, that is, the types from which this class is inherited separated by a colon:

classMyList (Length: Int): List, Serializable (...)

Tretes.The class may be inherited from one class or from several treit (Trait is a literal "characteristic feature", feature). Tretes are similar to classes in that they also define types, may also have members and inherited from other traits. The main difference is that the traits do not have constructors and, as a result, cannot have state (fields). It can be said that traits are familiar to all interfaces from the Java language, only functions in them can have implementations. The restrictions imposed on the traits make it possible to avoid the difficulties associated with multiple class inheritance.

External functions.Another "Expansion" mechanism of types in Kotlin is external functions (Extension Function - "Extension Function"). Such functions can be announced outside any class and to be called as if they were declared inside. Here is an example of an external function ad for type int:

fun.Int.abs (): int ( if(tHISreturn -This eLSE. rETURN THIS }

The type expandable by this function is indicated before it is named and separated by a point. This corresponds to the announcement of the "implicit" parameter, which inside the function is indicated by keyword tHIS. For example, in our example, the ABS () function expands the INT type, and an implicit parameter tHISis an integer. This feature can be called using the "Point" operation, as well as functions - class members:

val.x \u003d (-1) .abs ()

Such a syntax allows you to implement in classes only the necessary minimum functionality without harm to the readability of the program.

External functions are associated staticallythat is, not virtual (Virtual).

Control structures. When.

Kotlin supports traditional administrative designs for imperative languages if, forand whileon which we will not stop in detail, as well as the design when.- Operation of branching, which can be viewed as an extended version of the traditional operator switch:

when.(x) (1 \u003d\u003e Print ("One") 2, 3 \u003d\u003e Print ("Two or Three") eLSE.\u003d\u003e Print ("Unknown Number"))

To the left of the sign "\u003d\u003e" indicates the expression or list of expressions separated by commas, called condition. If a argument Designs when.(In our example, the variable x) is equal to at least one of these expressions, the body of this condition is performed, that is, the expression or block specified to the right of the sign "\u003d\u003e". Conditions are checked sequentially, downward. If none of the conditions are executed, the code specified after the word eLSE.. Unlike switch, using when.conditions are not labels, so it is not necessary to finish the body condition in a word break.

In addition to the simple comparison on equality, when.allows you to check the argument to belong a collection using the operation iN.:

when.(x) ( iN.sET \u003d\u003e PRINT ("IN SET") iN.1..10 \u003d\u003e Print ("1..10") eLSE.\u003d\u003e Print ("Default Branch"))

After the keyword iN.the expression that has any type that supports the Contains () method is indicated. In particular, a collection may be indicated (as in the first condition in this example) or gap (as in the second). The gaps can be formed both as integer and fractional numbers, and the extreme values \u200b\u200b(in this example 1 and 10) are included.

Another type of conditions is marked by a key word IS and allows you to check the type of argument. For example, check to which of the several types includes the value x, as follows:

when.(x) ( iS.String \u003d\u003e PrintLN ("String") iS.Int \u003d\u003e println ("int") iS.Array \u003d\u003e PrintLN ("Array of Double"))

Type System

Zero links.Kotlin language type system allows you to guarantee the absence of certain errors in programs, such as zero reference. Types in Kotlin are divided into containing nULLand not containing nULL. Types containing nULL, annotate a question mark:

fun.isempty (S: String?): Boolean (...)

Question sign After the type name (String) means that the link S indicates the class of class String or matters nULL . The result of the iSempty function, in turn, must be a boolean value and cannot matter nULLSince the appropriate type is not projected by the question mark.

return.s.LENGTH () \u003d\u003d 0 // Error: Range Zero Link

It is necessary to clearly check if it refers to the existing object:

I. f (s! \u003d nULL) { return.s.LENGTH () \u003d\u003d 0 // s exactly references to an existing object) eLSE.{ return True.} return.(S \u003d\u003d nULL) || S.LENGTH () \u003d\u003d 0 // Operator || Provides verification

Often there are long chains of calls, each of which can return nULL. As a result, we get several nested conditions that are checked, which returned each of the calls in the chain. To avoid clogging code, the operator is supported in Kotlin safe challengeindicating "?.":

A? .Getb ()? GetC ()? GETD ()

If A is not equal nULL, expression A? .GetB () returns a.getb (), and otherwise - nULL.

Automatic type of type.We have given an example of how the compiler takes into account the information contained in the conditions and allows you to retain already proven links. A similar mechanism automatically inserts the operation. bring typeIf earlier the corresponding condition was checked in the program. Type check operator (analog instanceOf.in java) in kotlin called iS.:

val.x: Object \u003d ... if(X is String) (Print (X.Length ()))

In this example, the reference x is checked to belong to the string type, and if the check has passed successfully, the string length is displayed. When you call the LENGTH () function, the compiler automatically inserts the deposit X to the string type, as it is safe in this place of the program.

Automatic type attachment works for all conditional structures: if, when., while, ||, &&, etc.

Functions of higher orders

Users of functional programming languages \u200b\u200bare familiar with functions of higher orders: A mechanism that allows you to transmit functions as an argument to other functions, record functions into variables, etc. As already mentioned, this mechanism makes it easier to create libraries. In object-oriented languages, higher order functions are usually emulated Using the Strategy pattern. For example, in order to implement filtering for collections of an arbitrary type, it is necessary to parametrize the function Filter () object, which "knows" to respond to the question whether to include this item to the resulting collection. This object is filtration strategy. In the functional language, you do not need to create a strategy - you can simply pass the function.

As an object-oriented language, Kotlin nevertheless supports higher-order functions. This means primarily that the function in Kotlin may be meaninghaving the appropriate type:

val.predicate: fun.(X: INT): Boolean \u003d ...

In this example, the Predicate variable has functional type « fun.(X: INT): Boolean, "that is, the value stored by it is a function that accepts an integer parameter and returning Boolean value. In particular, we can cause this feature:

val.yesorno \u003d Predicate (1)

This function can be used, for example, when filtering a set of integers:

fun.Collection .INTFILTER (Predicate: fun.(X: INT): Boolean): Collection (...)

And for arbitrary collections, you can generalize it using typical parameters (Generic):

fun. Collection .Filter (Predicate: fun.(X: T): Boolean): Collection ( val.result \u003d ArrayList () for(X. in this) if (Predicate (x)) result.add (x) return.rESULT)

(Here is only the naive implementation of the Filter () function. A more realistic implementation requires lazy calculations, but this topic goes beyond this article.)

The most interesting thing is to how to set the value of an argument having a functional type. For this, the already mentioned functional literals:

INTS.Filter ((x \u003d\u003e x% 2 \u003d\u003d 0))

In this example, the argument of the external function Filter () is a functional literal, that is, a short ad function. It is definitely in curly brackets, to the character "\u003d\u003e" follow the declarations of parameters, and after the body of the function, and the RETURN statement is not required, since the result is considered last expression In the body literal. Thus, the INTS collection will be selected only even numbersSince our literal returns true, only if the residue from dividing X by 2 is zero.

In the example above, the type of functional literal parameter is not specified, since the compiler will automatically lead it from the context. If necessary, types can be specified, but in most cases such a short record is possible and allows you to make the code much more readable.

For ease of use of functional literal literals, the following syntax conventions are adopted in Kotlin. First, if the functional literal has exactly one parameter, this parameter can not be announced, and it automatically receives the name IT (and its type is derived from the context):

INTS.FILTER ((IT% 2 \u003d\u003d 0)) // Call is similar to the previous example

Secondly, if the last argument when calling a function is a functional literal, it can be transmitted outside of round brackets, and if there are no other arguments, then the parentheses themselves can be omitted:

INTS.FILTER (IT% 2 \u003d\u003d 0) // Call is similar to two previous examples

Such a syntax allows you to record conversion of collections in a style resembling LINQ:

INTS.Select (IT * IT). WHERE (IT% 2 \u003d\u003d 0) // Among the squares of the elements of the collection // Select even

(Here the WHERE () function does the same as the FILTER () function.)

In addition, this convention makes challenges more similar to familiar control designs. We give another example. The Synchronized () feature receives two parameters: synchronization object (monitor) and function. During execution, the monitor is first captured, then in the block try..finally.a function is performed, and then the monitor is released:

fun.synchronized (L: Lock, Body: fun.(): T): T (L.Lock () try.{ return.body ()) finally.(l.unlock ()))

In order to trigger a fragment of a code with synchronization using this function, it is sufficient to write:

Synchronized (Mylock) (// code you need to perform)

This example shows how in Kotlin you can express the language to the language, which in Java is built-in.

Object-oriented languages

In the introduction mentioned libraries, work with which reminds the use of subject-oriented languages, that is, "small" languages, as if embedded Kotlin. An example is the library to describe modules, that is, the compilation units used in our language. The module is described assembly scenario - program on Kotlin, causing the function of the standard library; This script is performed during compilation. Consider an example of the assembly scenario:

val.homedir \u003d "..." module ("org.jetbrains.test") (// Announcement of the Depends module (MavenRepo (" [Email Protected]")) // Dependence of ImportNameSpace (" java.lang ") // Import default ImportNamespace (" Org.junit ") // Import default SourceRoot (" $ Homedir / SRC ") // Path to the source files TestSourceRoot (" $ Homedir / Tests ") // Path to tests)

Despite the fact that we have an ordinary program on Kotlin, it looks like a program on a specialized language intended for a declarative description of the modules. Such an approach to the description of the data structures is very popular in Groovy and other dynamic languages, since it avoids bulky and difficult readable descriptors written on XML. In Groovy, this approach is known as Builders. A bright example of its use is the GRADLE library.

Compared to Groovy and other dynamic languages, an important distinction of the internal DSL in Kotlin is that with the same shortness of syntax, type system statically guarantees Program correctness.

Consider the principle of implementing statically typed Builders in Kotlin. For these purposes, a small fragment of the tongue of assembly scenarios is a sufficient: descriptions of dependencies between modules in the simplest case. So, the modules themselves are described by the following classes:

// Abstract module abstract Class. Module (Name: String) ( val.dependencies: List \u003d ArrayList ()) // Module consisting of classes written on Kotlin classKotlinModule (Name: String): Module (Name) ( fun.dependency (Module: Module) (Dependencies.add (Module)) // Module based on the Maven repository classMavenRepo (Name: String): Module (Name) (...)

We define the Module () function creating a new module:

fun.module (Name: String, Init: fun.Kotlinmodule. (): Unit): kotlinmodule ( val.result \u003d KotlinModule (Name) result.init () return.rESULT)

This function is a higher order function, since the init parameter itself is a function, and exterior Function: This is said by the type of kotlinmodule, specified in front of the (empty) list of parameters in the functional type. This means that the Module () function can be called as follows:

Module ("org.jetbrains.test") (// body function init)

It looks like an example of a script that we have already seen. Note that an implicit parameter is available inside the functional literal tHIStype kotlinmodule (since this literal is the type "external function"), and we can use it:

Module ("Org.jetbrains.Test") ( tHIS.Dependency (MavenRepo (" [Email Protected]")) tHIS.Dependency (Anothermodule) // ...)

It remains to notice that tHISAs usual, you can omit, and we get exactly the same syntax as in the example of the script shown in the start of this section:

Module ("Org.jetbrains.Test") (Dependency (MavenRepo (" [Email Protected]")) Dependency (Anothermodule) // ...)

Similarly, many declarative languages \u200b\u200bcan be implemented, including markup languages, such as HTML. At the same time, instead of tags, calls for higher-order functions will be used, and the correctness of the use of such tags, as well as their attributes, will be guaranteed by the type system:

HTML (HEAD (TITLE (+ "XML Encoding with Kotlin")) Body (H1 (+ "XML Encoding With Kotlin") P (+ "This is sometext. For more see the" A (href \u003d "http: // jetbrains.com/kotlin ") (+" Kotlin Home Page ")))

We reviewed several of the most interesting features of the Kotlin language, but the frameworks of the language as generalized types are left beyond the frameworks (Inline Function), the type of types during execution (REIFIED TYPE), support for delegation, redefine operators, etc. These opportunities, as well as the progress of the project, can be found on the project page.

The language is under development, and while the specification is not recorded, we make every effort to get and consider the opinions of our future users.

Literature

  1. Bloch J. Effective Java. SECOND EDITION. - Prentice Hall, 2008.
  2. Gamma E., Helm R., Johnson R., Wlissides J. Taking object-oriented design. Design patterns. - SPb.: Peter, 2007.
  3. Troelsen E. Programming Language C # 2008 and Platform. NET 3.5. - M.: Williams, 2010.

Except in cases of inconsistent separate compilation. - Approx. author.

IS also allows you to conduct comparison with sample (Pattern Matching) - approx. author.

Andrey Breslav. ([Email Protected]) - Leading Kotlin Developer, JetBrains.



Did you like the article? Share with friends: