Kotlin M11 is Out!

Today we are releasing a new milestone: Kotlin M11, which brings such long-awaited features as secondary constructors, a first glimpse of true reflection support for Kotlin and much more.

Language Changes

M11 brings quite a few language changes, some of which are breaking changes and/or deprecation of old ways of doing things in favor of new ones. Some of your code may break, but we’ve done our best to make your transition path as smooth as possible.

Multiple Constructors

This feature has been most awaited by Android developers, because subclassing standard view classes on Android requires having more than one constructor. Now you can do that:

Please refer to the user docs and the spec document for more details.

Prefixes For Initializer Blocks

Another change, also related to constructors, is prefixing initializer blocks with the soft-keyword init.
The main reason for this change is that the formerly used syntax (where just curly braces in a class body denoted an initializer block) didn’t work out too well when an initializer followed a property declaration (which is pretty common):

An error was reported on the call of baz(), because the initializer looks exactly like a trailing lambda passed to it. The only workaround was to put a semicolon after the property initializer, which looks rather unnatural in Kotlin. So, since M11, we require init before the initializer block:

The old syntax is deprecated, i.e. you’ll get a warning, not an error. Also, the IDE provides an Alt+Enter quick-fix action to convert the old syntax to the new one, which has an option to bulk update the whole project.

See user docs for more details.

Companion Objects (Class-Objects Rethought)

As you all probably know, Kotlin classes do not have static members. Instead there may be a special singleton object associated with a class, which we used to call “class object” ‐ a rather unfortunate term. So, we somewhat redesigned the concept, and, with your help, chose another name for it: companion object.

The unfortunate wording was not the only reason for this change. In fact, we redesigned the concept so that it is more uniform with normal objects.

Note that a class can (and always could) have many objects (usual, named singletons) nested into it:

Since M11, one of these objects may be declared with the companion modifier, which means that its members can be accessed directly through class name:

Accessing members of Obj1 requires qualification: KotlinClass.Obj1.foo(). For members of Obj2 the object name is optional: KotlinClass.foo().

One last step: the name of a companion object can be omitted (the compiler will use the default name Companion in this case):

Now you can still refer to its members though the name of the containing class: KotlinClass.foo(), or through full qualification: KotlinClass.Companion.foo().

As you can see, unlike what we used to have with class objects, companion objects are completely uniform with normal objects.

Another important benefit is that now every object has a name (again, Companion is used when the name of a companion object is omitted), which enables writing extension function for companion objects:

See user docs here.

Function Expressions

Kotlin has higher-order functions, which means that you can pass a function around as a value. Before M11, there were two ways of obtaining such values: lambda expressions (e.g. { x -> x + 1 }) and callable references (e.g. MyClass::myFun). M11 introduces a new one, which is very logical, if you think about it:

So, you can use a function, in its traditional syntactic form, as a value. See user docs and the spec document for more details.

Lambda Syntax Restricted (for future enrichment)

Among other things, function expressions enable us to make a step toward supporting multi-declarations in parameters of lambdas. The final goal (not implemented yet) is to be able to, say, filter a list of pairs with the syntax like this:

Here, (a, b) is a multi-declaration, i.e. a gets the first component of each Pair object, and b gets the second one. Currently, multi-declarations are not supported, but we deprecated some of the syntactic forms of lambdas to drop them in M12 and make the multi-declaration syntax possible.

What is deprecated:

  • specifying return types of lambdas, e.g. { (a: Int): Int -> a + 1 }
  • specifying receiver types of lambdas: { Int.(a: Int) -> this + a }
  • using parentheses around parameter names of lambdas: { (a, b) -> a + b }

Whenever you really need one of these, please switch to using function expressions instead.

The IDE provides a quick-fix that migrates your code automatically.

Labeled Returns in Lambdas

For a long time there was a restriction on using return expressions in lambdas: a local return was only allowed if the lambda has an explicit return type specified. This was caused by a limitation in the type inference algorithm. Now, the restriction is removed, and we can use local returns freely:

Import Semantics Changed

Importing is one of the least-visible language features for IDE users, but it has a great influence on how tools work, and occasionally on the users, too.
In M11 we made the order of *-imports (also called “on-demand imports”) insignificant, and made some other tweaks that enabled us to implement efficient automatic management of import directives in the IDE.

Reflection

Implementing Kotlin-specific reflection (rather than making you use Java reflection on Kotlin classes) is a long-running project that has required a lot of work in the compiler. Essentially, we have to factor out a large portion of the compiler and ship it as part of the runtime. This includes: loading Kotlin-specific metadata from the binaries, representing Kotlin symbols as objects (historically, we call them descriptors), loading Java declarations as Kotlin ones (because Kotlin reflection should work on Java objects too) and so on.

At last, we present the first results of this work: the ability to introspect properties, provided through a new kotlin-reflect.jar that ships with the compiler (a lot more functionality will be added soon).

The New Reflection Jar

We ship kotlin-reflect.jar separately (not as part of kotlin-runtime.jar), because it is rather big at the moment: about 1.8MB. We will look into reducing its size, but it is likely to always be rather substantial, so making everyone always ship it with their applications is not an option (especially for Android developers).

As a consequence, you may need to add this jar to your classpath, if you use property literals (::propertyName). The M11 compiler will yield an error if you don’t, but later this requirement will be relaxed. The IDE will offer you a quick-fix action that adds the jar automatically to your project.

Class Literals

To obtain a reflection object for a class in Kotlin, use the following syntax:

You get an instance of KClass<MyClass>, which you can introspect, e.g. get its properties.

See more in the user docs.

Compatibility with Java Reflection APIs

Kotlin reflection API works both for Kotlin and Java classes, and you can “convert” from Kotlin to Java reflection objects and back. For example, you can say kClass.java and get a java.lang.Class instance, and vice versa: jlClass.kotlin gives you a KClass instance.

@Nullable and @NotNull in Java

As always, Java interop is a big priority for us, and this time we are improving on the platform types feature we shipped in M9: now the compiler issues warnings on misuse of Java values annotated as @Nullable and @NotNull. This is not as strict as it used to be before M9, but it doesn’t break as often either.

Next step would be to issue Java nullability errors in a safe way (so that an error can always be fixed reasonably), and this is planned for the next milestone.

Android Extensions

Good news for Android users: M11 brings a useful extension that makes Android development in Kotlin easier.

We all know about findViewById(). It is a notorious source of bugs and unpleasant code which is hard to read and support. In Java the way around this problem is through libraries such as ButterKnife and AndroidAnnotations, which rely on JSR 269, but it is a javac-specific API and is not supported in Kotlin (yet).

Since M11, Kotlin has its own solution to the findViewById() problem, which does not require JSR 269: the new kotlin-android-extensions plugin for the Kotlin compiler allows you to access views in a type-safe way with zero extra user code (no annotations or other such things) and no runtime libraries required.

To use this extension, you need to enable it in your Gradle build and install an extension plugin into your IDE. See more here.

IntelliJ IDEA Support

More improvements and features for IntelliJ IDEA

Refactorings and Intentions

The following refactorings and intentions are now available:

  • Introduce Property
    Ability to introduce property and to define whether we want an initializer, a getter or lazy property
  • introduce-property

  • Create from Usage with Java Interop
    It is now possible to invoke “Create from usage” on Java types being used in Kotlin files.
  • introduce-property

  • Receiver to Parameter Conversion
    A special case of Change Signature refactoring, whereby a parameter can be refactored to a receiver, thus allowing
    converting a function that takes a parameter of type T into an extension function of T. It also allows for the reverse, whereby a receiver can be transformed into a parameter.

    receiver-parameter

  • Function to Property
  • Ability to convert a function to a property and vice versa

    function-property

  • Unused declarations
  • Unused declarations inspections is now available project wide, allowing these to be highlighted in any context.

Evaluate Expression

We now have the ability to evaluate lambda expressions and anonymous objects in the debugger:

evaluate-lamda

KDoc Support

We now have a fully fledged language to provide inline documentation. It is called KDoc and based on a combination of JavaDoc and Markdown. The full reference is available online. With M11, IntelliJ IDEA provides support for KDoc via completion, validation and refactoring support.

Standard Library

One of the big changes in the Standard library is renaming streams to sequences. This was done so as to avoid confusion with Java 8 streams.

will generate an infinite lazy sequence of numbers starting at 1. There are also extension functions allowing to convert existing iterables to sequences

There have also been several bug fixes in the standard library.

In addition the team contributed to some updates to RxKotlin, making it more idiomatic in light of the recent changes in Kotlin.

Last but not least, we have also revamped the standard library API reference, which is now available on the Kotlin Web site.

JavaScript Support

The JavaScript backend now has better support for inline functions. We’ve also made it simpler to reuse libraries targeted at JavaScript through the new concept of “JavaScript binaries”, which will be covered in more detail soon.

Other changes and improvements

In addition to the above, this release also brings:

  • Gradle Changes
    Kotlin and Java files can now reside in a single source folder
  • Bug fixes and compilation speed improvements
  • Over 220 bug fixes since M10 as well as many external pull requests from the community.

As always, you can update the plugin in IntelliJ IDEA 14 (or earlier versions) if you have a previous version installed, or install directly from JetBrains plug-in repository. You can also download the standalone compiler from the release page.

About Andrey Breslav

Andrey is the lead language designer of Kotlin at JetBrains.
This entry was posted in Releases. Bookmark the permalink.

82 Responses to Kotlin M11 is Out!

  1. Pingback: 1p – Kotlin M11 | Profit Goals

  2. Paweł says:

    Great changes for Android Developers! Kotlin Android Extensions and multiple constructors support are so good.

    “Gradle Changes
    Kotlin and Java files can now reside in a single source folder”
    … so now better practice is to put them under src/java or src/kotlin folder?

  3. Wow! Big release here! Great work guys!

    The plugin for 14.0.3 is not yet out though.

    Thank you!

  4. Guangyu HE says:

    Great work. Thansk.

    It seems the size of Kotlin reflection-jar is too large. I have a question:
    In which situations, we should use Kotlin-reflection instead of Java-Reflection?

    • Java reflection is less precise than Kotlin reflection: it does not know about properties, for example. But if it works OK for you, you can stick to it

      • Rostislav says:

        Dex method count for kotlin reflection and dependencies: 5313 for com.google.protobuf and 7387 for kotlin reflect. 12.5k is a bit too much for android if you don’t want to use multidex or proguard(they both increase build time by an order)

      • Guangyu HE says:

        My code depends on functions ::, which is now moved to Kotlin-reflect.jar.
        If I want to use :: function only, and don’t want to depend on Kotlin-reflect.jar, what should I do?

        • Alexander Udalov says:

          You can use callable references as pure functions without reflection freely. The IDE inspection gives a false warning at the moment, this will be fixed (see KT-7059)

  5. Dmitry Romanov says:

    Wow! Awesome! You did a great job!

    So it is the companion in the end. Nice!

    The main question for me, is when the language is going to be frozen? I mean, knowing the release plans would be better… =) But at least, what are the plans for feature freezing?

  6. Stephen Colebourne says:

    Reading the primary/secondary/init constructors in the docs, it all reads like a bit of a mess. Particularly, the “class Customer private () { … }” is ugly.

    It would be much more consistent to just have one syntactic approach, based on the secondary one (and Java). Take constructors out of the class definition and treat them as proper methods (which they should be). Brevity, as in a method embedded within the class header, is losing clarity.

    Using “new” as the keyword instead of “constructor” would be nicer too.

    • Paweł says:

      Constructors in class definition are quintessence of Kotlin (e.g. data classes) and code is much more clear.

      Agree that “constructor” is a bit too long, maybe “construct” or “constr” acronym would be better.

    • Mohammad Shamsi says:

      +1 for the separation of class and its constructor(s). Although with the changes in M11 they can, optionally, be separated:

      I would also vote for “new” or “make” instead of “constructor”. both are shorter and nicer.

  7. Yoav Sternberg says:

    kotlin-android-extensions doesn’t work for me. it doesn’t generate the files.

    • It shouldn’t generate any files, you can simply call activity.textView if your layout XML file has such a control.

    • Dmitriy Voronin says:

      imports are ok for me, but plugin can’t parse layouts. Started discussion on kotlin forums: https://devnet.jetbrains.com/message/5537758#5537758

    • Henri Sweers says:

      Doesn’t work for me either. I have the plugin installed as well. No lint errors, but the actual compilation (using gradle-aware make in the IDE or gradle wrapper from the command line) results in this:

      :palettehelper:compileDebugKotlin
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (40, 8): Unresolved reference: kotlinx
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (64, 9): Unresolved reference: toolbar
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (65, 9): Unresolved reference: toolbar
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (109, 62): Unresolved reference: image_view
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (219, 13): Unresolved reference: grid_view
      e: /Users/hsweers/dev/android/PaletteHelper/palettehelper/src/main/kotlin/io/sweers/palettehelper/PaletteDetailActivity.kt: (220, 13): Unresolved reference: grid_view

      FAILED

    • Hi,I encountered the same problem, would you solve it? Thanks.

      • snwr says:

        I had this problem too, and the solution is:

        [build.gradle]
        buildscript –> dependencies –> add the line below:

        classpath “org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version”

  8. Dmitry says:

    Thank you very much, everything looks wonderful!
    Really looking forward to be able to use that
    pair.filter {(a,b) -> …}
    stuff.

    Also I miss from time to time a support for type aliases (helps when dealing with lots of hierarchical and templated code). You once said that it is on your list, but with minor priority, I hope this will not fall off the radar :)

  9. Даниил Водопьян says:

    I am sorry to raise the discussion again, but I cannot pass by.
    So finally the syntax is:

    And now I as a user wonder how should I add an extension to the ‘companion object’

    So the only proper way to do things would be to allow referencing to the companion object with the default name Consumer.Companion

    Maybe you already considered that and it will be in M12. Maybe you disagree with the argument and I should post a bug ticket for further discussion.

    • Даниил Водопьян says:

      And so the #Kotlin puzzle began!

    • I can’t see the problem here: you have a named object, its name is HeyObject, why do you want to refer to it by some other name (Companion)?

      • Даниил Водопьян says:

        Because for me it is an object, related to class Consumer, and that’s all I care about.

        Something tells me that whatever we do about it, named companion will become an anti pattern for Kotlin

  10. Jayson says:

    jackson-kotlin module will update soon, need to take a look at the constructor changes, reflection api and more. Weekend-project.

  11. Mohammad Shamsi says:

    Great Job. Awesome features.

  12. Pingback: Yested updated to Kotlin M11 | Yested Framework

  13. Pingback: 1p – Kotlin M11 is Out | Profit Goals

  14. Pingback: 1p – Kotlin M11 is Out – Exploding Ads

  15. Pingback: Kotlin M11 发布,基于 JVM 的编程语言 | 技术迷

  16. ac says:

    Are you going to have formal Video tutorial for Android developement?

  17. Matthew Wear says:

    Such great work!!

    I am having one issue. A good chance I’m doing it wrong, but synthetic properties are doing unexpected things for me import kotlinx.android.synthetic..*

    Seems like if you have multiple instances of the same fragment on the activity, in my case a ViewPager with FragmentStatePagerAdapter, then something is awry. Almost seems like there are not multiple instances of my views in the activity, only the last Fragment created seems to be able to change its views state.

    I haven’t look at the source, but almost seems like there is not a hidden caching function generated for each fragment.

    Thank you so much.

  18. Pingback: Kotlin M11 Lands: Could this JVM Newbie Become Your Favourite Android Language? | Voxxed

  19. Pingback: JVM-Sprache Kotlin erreicht 11. Meilenstein - jaxenter.de

  20. Pingback: Google Places API for Android and iOS, Android Wear device locator, and Atlassian’s new Snippets feature—SD Times news digest: March 20, 2015 - SD Times

  21. Great work Kotlin team! We are excited to experiment with M11

  22. Olivier Binda says:

    Thanks for M11 (secondary constructors means less java and more kotlin :).

    And many thanks for the painless transition. :)

    Great job !

    What are the major features that you want to put in kotlin for 1.0 ?
    Will there be some annotation processing support ?

  23. Salomon BRYS says:

    Any ETA for incremental compilation support in Android ?
    Having to recompile the hole app for a single line change is a huge waste of productive time…

  24. Oliver Thomas says:

    First off, congrats on the release. I’m a very new user, but liking the language so far, with a few annoyances (mostly related to Java interop).

    I don’t know if I’m missing the obvious, but since the switch to sequences, all the higher order functions I’ve used on iterable Java types (map, fold etc,) are flooding me with deprecation warnings, and I can’t see an easy way to convert them from Iterator to Sequence. I can chain a sequence() call to the Iterator to****() extension methods, but they are themselves deprecated. Do I just ignore these warnings when dealing with Java iterables?

    Thanks for Kotlin!

  25. Matt Gile says:

    We love Kotlin and have been using it since M4 on the server side, great to see the language progressing. We use Dynamic Transforms and Dependency Injection quiet a bit and having a simple class literal is key for us. The MyClass::class syntax is great but I am surprised it returns a kotlin.reflect.KClass object and not a java.lang.Class object. Can I suggest something like

    MyClass::java -> java.lang.Class
    MyClass::kotlin -> kotlin.reflect.KClass

    OR

    MyClass::class -> java.lang.Class
    MyClass::klass -> kotlin.reflect.KClass

    Right now I know I can do

    MyClass::class.javaClass

    Finally if I just used the java class literal in kotlin maybe it would not require the reflection package. (not a problem on the serverside, but for android devs)

    • Alexander Udalov says:

      This is a language feature and the language semantics should not depend on the particular platform. Also Java reflection doesn’t suit our needs because everything is different in Java, including the type system and various kinds of symbols that need to be reflected (Java has methods/fields vs Kotlin’s functions/properties, for example).

    • Could you share some use cases you have for class literals: do you use them mostly as annotation arguments, or maybe mostly as arguments to a few particular API methods?

      • Matt Gile says:

        Java

        diSession.getInstance(MyClass.class)
        //-> returns an instance of MyClass constructed using Dependency Injection
        transformer.transform(input,MyClass.class)
        //-> transforms the input object into MyClass if it can

        Kotlin

        diSession.getInstance(MyClass::class.javaClass)
        diSession.getInstance(javaClass())
        ...

        Thank you

        • Off the top of my head, I’d suggest to create extensions on diSession and transformer that take KClass and transform it to java.lang.Class internally.

          The result would be:

          BTW, I strongly suspect that MyClass::class.javaClass is a bug, because it always returns java.lang.Class<KClass>, and what you meant is MyClass::class.java

          • Matt Gile says:

            You are right, MyClass::class.javaClass, is a mistake. It is too easy to make of an mistake and another reason I feel kotlin needs to include clean java class literals. Yes know know I can also use reified generics, but his requires me to augment all of the place classes are passed with extension functions.

          • Matt Gile says:

            Another reason for Java Class Literals in kotlin is to skip the overhead of creating a KClass just to get a reference to the Java Class Literal.

  26. Micah Zoltu says:

    I’m eagerly awaiting to hear more about JavaScript binaries!

    • Michael Nedzelsky says:

      I hope something to read about Kotlin/Javascript libraries will be ready in near future (beginning of the next week).

  27. Boban says:

    Go is coming to android. Go has coroutines. Kotlin is the only reason why I would code for Android. I hope that Kotlin will have async-await in near future.

  28. Tealsens says:

    It’s so great that the secondary constructor was implemented! Thank you for adding this feature, and now I can choose Kotlin instead of Scala.

    I love Kotlin because it’s truly simple and has tiny runtime.

  29. TB says:

    Is there a way to not create auto property on constructor? Because at whatever constructor the parameters will always be auto properties.

  30. Pingback: How I wrote my first iOS app while learning Kotlin for Android Development | Honey, Ice & Jelly

  31. TB says:

    What is the equivalent of Java 8 :: for passing method as an argument in Kotlin? Currently I can only use lambda to overcome this.

  32. Pingback: Roadmap de #kotlin | Kotlin.es

Comments are closed.