Kotlin 1.1-M04 is here!


We are glad to present you the fourth milestone of the upcoming Kotlin release. We’re wrapping up the development of the version 1.1, with the final release planned for Q1 2017. Most features are already in decent shape, so it is a good time to try it and give us your feedback. We will appreciate it a lot!

As with other milestone releases, we give no backwards compatibility guarantees for new language and library features. Anything introduced in milestone releases of 1.1 is subject to change before the final 1.1 release.

Please do share your feedback regarding the new features or any problems that you may run into with this release, via YouTrack, forums and Slack.

This milestone brings a significant rework of coroutine syntax and semantics, making coroutines simpler and more flexible. It also contains standard library enhancements, new language features and compiler plugins, numerous features and improvement in the JS backend, and many other fixes and updates.
The new release also includes all features introduced in the Kotlin 1.0.6, including updates for compatibility with Android Studio 2.3 Beta 1.

The full changelog is available here and some key changes are listed below:

Coroutines

We have significantly re-thought the coroutines design, making it simpler, composable and more powerful:

  • All suspending and coroutine builder functions now have intuitive signatures (no more weird transformations to memorise).
  • There is only one basic language concept of suspending functions and the corresponding suspending function types. The special coroutine keyword was dropped. The coroutine is now simply an instance of a suspendable computation that is started using startCoroutine function from the standard library.
  • Complex suspending functions can be composed out of more primitive suspending functions. In this release they can tail-call other suspend functions, but this restriction will be lifted in the future.
  • Suspending functions can be defined to wrap any callback-style API and can be freely used inside any asynchronous coroutine. The controllers are not needed anymore. The generate and yield pair, that builds synchronous sequences, restricts suspensions inside generate blocks using @RestrictsSuspension annotation.
  • Type inference for coroutines is now implemented. You can omit types in most use-cases for coroutine builders and the types will be inferred automatically.

The classical await suspending function can now be implemented via a tail-call to the suspendCoroutine suspending function that is a part of the standard library:

The corresponding builder is called async and implemented via the startCoroutine function:

And they can be used together to write a more naturally-looking code with futures:

However, futures are just one of many supported use-cases for coroutines. The full overview of the coroutine implementation and their usage samples are available in the revised KEEP document.

We think that now we have got a great design of coroutines for Kotlin, but we realize that it has not been battle-tested enough. Therefore we are going to release it in 1.1 under an opt-in incubation flag. Starting from this milestone you’ll get “This feature is experimental: coroutines” warning when using coroutines. You can turn off this warning with -Xcoroutines=enable compiler flag or disable this features with -Xcoroutines=error compiler flag. The corresponding setting is also available under Kotlin compiler settings in the IDEA. To set this option for a gradle project you can add kotlin.coroutines=enable or kotlin.coroutines=error to local.properties file at the root of project.

If you are using kotlinx.coroutines library please use updated version 0.2-alpha-1, adapted to the newest changes in the coroutines design. This version also introduces yieldAll method in the generate scope. Please see the readme file for further details.

Language features

Type for properties can be inferred from getter

For example in the code below the type for the property foo will be inferred as String. See the issue KT-550 for some more details.

Floating point related features, fixes and improvements

Floating point number comparisons now use IEEE 754 compliant comparison where the type is known statically to be Double or Float. For ranges of floating point numbers we’ve introduced specialized ClosedFloatingPointRange interface, which provides its own comparison method, so that extension operations employing ranges, like coerceIn, could be implemented on top of that. Its instances are obtained with the operator .. invoked on two Float or Double values. See KT-4481 and KT-14651 for details.

Interception of delegated property binding

It is possible now to intercept delegate to property binding using the provideDelegate operator.
For example, if we want to check property name before binding, we can write something like this:

Here method provideDelegate will be called in constructor initializer for class MyUI. So, we can check property consistency at the moment of creation. Earlier such checks were only possible at the moment of calling getter or setter.

Unfortunately, the feature is not yet properly documented, but you can use this draft document as an initial reference.

Enhanced nullability of some JDK methods

Some functions in JDK have a nullability contract defined in the documentation, some do not accept null values, some never return null, and yet others can return null sometimes.
Unfortunately, the JDK does not use any annotations to express such contracts and only states them in the docs. Once before 1.0 we used an external annotations artifact for the JDK which could be supplied to the compiler to alter the signatures of JDK functions, but that approach wasn’t reliable enough.

Now we’re introducing another approach: embedding the information required to enhance the JDK signatures directly into the compiler. As a first step we cover the nullability of a small subset of the API:

  • java.util.Optional factory and member functions:
    • of: that doesn’t allow null values
    • ofNullable, it takes a nullable value, and return an Optional of non-nullable type.
    • get always return non-nullable value.
  • java.lang.ref.Reference and all of its inheritors, like WeakReference and SoftReference:
    • get returns a nullable value, as it can become null at any moment if the referenced object is garbage collected.
  • default methods of JDK’s Iterator, Iterable, Collection, List, Map which are exposed as platform-dependent functions of Kotlin builtin collection interfaces.
  • java functional types, now they have non-platform types in their invocation methods when they’re constructed with non-platform types.

These enhancements are safe in most cases. In particular, they are safe when the enhanced type becomes more specific (non-nullable) in return position or more general (nullable) in parameter position. But when the type is changed in the opposite direction, the change will be breaking.
We strive not to introduce such breaking enhancements unless not respecting the correct nullability would lead to an exception in runtime. So for example Optional.of now takes a non-nullable argument which is more restrictive, but trying to pass null to that method would result in an exception anyway.
On the other hand, we decided not to specify the correct nullability for File.listFiles which actually can return null sometimes, because in most cases there’s no meaningful fallback other than to throw another exception.

Other changes

  • Problem of using a non-public member from a public inline function could now be resolved with the @PublishedApi annotation. When it’s applied on an internal member, it becomes effectively public and available to invoke from a public inline function.. See KT-12215 for details.
  • const val is now inlined at the call site (see KT-11734)
  • SAM conversions have now the same priority in overload resolution as regular members. That fixes KT-11128 and alike.
  • We consider our choice of mod name for % (remainder) operator a mistake with some not so nice consequences (see e.g. KT-14650). Therefore we decided to introduce rem operator, deprecate the mod and provide all tools to make this transition smooth.

Standard library

String to number conversions

There is a bunch of new extensions on the String class to convert it to a number without throwing an exception on invalid number: String.toIntOrNull(): Int?, String.toDoubleOrNull(): Double? etc.
Beware that these functions will box resulting numbers before returning them, as the return type assumes it.

Also integer conversion functions, like Int.toString(), String.toInt(), String.toIntOrNull(), each got an overload with radix parameter, which allows to specify the base of conversion.

We would like to thank Daniil Vodopian for his substantial contribution to the development of these functions.

onEach

onEach is a small, but useful extension function for collections and sequences, which allows to perform some action, possibly with side-effects, on each element of the collection/sequence in a chain of operations.
On iterables it behaves like forEach but also returns the iterable instance further. And on sequences it returns a wrapping sequence, which applies the given action lazily as the elements are being iterated.

Thanks to Christian Brüggemann for the initial prototype.

JavaScript backend

external instead of @native

From this milestone @native annotation becomes deprecated and instead you have to use external modifier.
Unlike the JVM target, the JS one permits to use external modifier with classes and properties.
Note, that you don’t need to mark members of external classes as external: this modifier
is automatically inherited by the members. So, instead of

you can write

Improved import handling

You can now describe declarations which should be imported from JavaScript modules more precisely.
If you add @JsModule("<module-name>") annotation on an external declaration it will be properly imported to a module system (either CommonJS or AMD) during the compilation. For example, with CommonJS the declaration will be imported via require(...) function.
Additionally, if you want to import a declaration either as a module or as a global JavaScript object, you can use @JsNonModule annotation

Let’s see the full example below. You can import jQuery library to a Kotlin source file like this:

In this case, JQuery will be imported as a module named jquery and alternatively, it can be used as a $-object, depending on what module system Kotlin compiler is configured to use.

You can use these declarations in your application like this:

You can check the generated JS code for this snippet for the CommonJS and “plain” module systems here.

How to Try It

In Maven/Gradle: Add http://dl.bintray.com/kotlin/kotlin-eap-1.1 as a repository for the build script and your projects; use 1.1-M04 as the version number for the compiler and the standard library.

In IntelliJ IDEA: Go to Tools → Kotlin → Configure Kotlin Plugin Updates, then select “Early Access Preview 1.1” in the Update channel drop-down list, then press Check for updates.

The command-line compiler can be downloaded from the Github release page.

On try.kotlinlang.org. Use the drop-down list at the bottom-right corner to change the compiler version to 1.1-M04.

Merry Kotlin!

This entry was posted in Releases and tagged , , , . Bookmark the permalink.

17 Responses to Kotlin 1.1-M04 is here!

  1. Salomon says:

    Great work JB !

    Is there a reason why Kotlin 1.1-M01 and 1.1-M02 are available to install via SDKMan! but not 1.1-M03 & 1.1-M04 ?

    • Ilya Chernikov says:

      Thanks for pointing out!
      Should be fixed now for M04. Please report if there are any problems.

  2. nichteben says:

    Can you help on this?:

    “Error:Failed to resolve: org.jetbrains.kotlin:kotlin-stdlib:1.1-M04”

    • Ilya Chernikov says:

      How you’re trying to use it?
      If you’re using gradle or maven, please add http://dl.bintray.com/kotlin/kotlin-eap-1.1 as a repository first.

      • nichteben says:

        I’m using default android gradle file with kotlin integration through kotlin plugin (newest)
        These are the gradle entries:

        build.gradle (project)

        ext.kotlin_version = ‘1.1-M04’
        repositories {
        jcenter()
        maven { url ‘http://dl.bintray.com/kotlin/kotlin-eap-1.1’}
        }

        build.gradle (module)

        compile “org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version”

        Note that it works flawlessly with the following line (old kotlin version):

        • nichteben says:

          Also this:

          classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version”

        • Ilya Chernikov says:

          You probably haven’t specified the eap repo in the main repositories section (as opposed to the buildscript section). By default, it lists only maven central (I think), so it worked with 1.0.5, but 1.1-M04 is not published there, while it is not a final release of 1.1.

  3. Sebastian Millies says:

    Thank you, I am really looking forward to the 1.1 release. With regard to coroutines, there seem to have been many substantive changes between M03 and M04. Can you say something about the background of that? You say it’s simpler and more flexible, but perhaps other considerations have also come into play (like facilitating having stackful coroutines at some time in the future, or integrating with Quasar?)

    Anyway, by way of exercise I have taken the kotlinx-coroutines library and used it to implement tree-traversal in a manner identical to what one could do in Python, written a JUnit test in Java to demonstrate seamless Kotlin-Java-integration, and compared the whole thing to an approach based on Java streams, which turns out not to be lazy enough. I found the experience very pleasing, if anyone’s interested, the write-up is at http://sebastian-millies.blogspot.de/2016/10/lazy-tree-walking-made-easy-with.html

    • elizarov says:

      The original coroutines were centred around restricted use-cases like generate/yield. They were not composable for asynchronous use-case where you might have different libraries with asynchronous computations (rx, futures, async io, etc) and different ways to represent asynchronous computations (rx, futures, etc). You could not freely mix and match them. It was all quite restricted and non-composable because of the controller approach. The second revision brings this composability onto the table by getting rid of controllers, while retaining highly efficient implementation for restricted generate/yield cases. Support for stack-full coroutines and potential integration with Quasar are all nice side effects and a direct consequence of composability.

  4. Raman Gupta says:

    In your coroutine example, you call original.await() inside the async block. However, your definition of await is not an extension on Future, but rather a method that takes a CompletableFuture as an argument. Am I missing something or is the example incomplete/incorrect?

    • elizarov says:

      It is a matter a style. await is just a library function and you can define it both as extension and as a function taking completable future. We are moving to extension style. The fresh version of kotlinx.coroutines is already released with extension style and the next revision of coroutines description document will use extension style future.await() in its examples.

  5. When are tuples coming back?

    This was the biggest drop from pre-1.0 Kotlin in terms of every day, practical usage. Outside of all the fancy coroutine stuff the team’s working on (great long-term investment)…. tuples have been our #1 most-used language feature in 2016 in Swift, and finally coming to our C# back-end with C#7.

    There’s so many times when a group of variables only make sense together (ie: you have results of different kinds, and you either have them all or not), and tuples are the perfect expression of these. You do NOT want to have to define explicit types for these because they are single-location only (ie: the variables only live together in that one place, makes zero sense to group these into an explicit type as you guys recommend using data classes https://blog.jetbrains.com/kotlin/migrating-tuples/, nor do you want to give any explicit name to this grouping – you want the naming to come out of the tuple variables themselves).

    Example (Swift):
    var onboardingItems:(featuredItems:[FeedItemVM], regularItems:[FeedItemVM])

    When are these coming back?
    Our Android Kotlin codebase is direly missing them.

    • Sébastien Deleuze says:

      Tuples are also my #1 missing feature.

    • If you don’t mind, I’ll read this as “are tuples coming back?” rather than “when are they coming back?” :) The answer is: we’ll see what we can do, but can’t give a definite answer right now. Thanks for your input.

  6. Grant says:

    Is there any documentation related to JSR-223 scripting support shown in the changelog?

Comments are closed.