M10 is out

Right before the festivities start, we’ve managed to release the next milestone of Kotlin, adding dynamic types and more. Let’s see what M10 brings us.

Language enhancements

Some improvements in the language, in particular:

Reified type parameters for inline functions

Before M10, we sometimes wrote code like this:

1

2

3

4

5

6

7

fun<T>TreeNode.findParentOfType(clazz:Class<T>):T?{

varp=parent

while(p!=null&&!clazz.isInstance(p)){

p=p?.parent

}

returnpasT

}

Here, we walk up a tree and use reflection to check if a node has a certain type. It’s all fine, but the call site looks a little messy:

1

myTree.findParentOfType(javaClass<MyTreeNodeType>())

What we actually want is simply pass a type to this function, i.e. call is like this:

1

myTree.findParentOfType<MyTreeNodeType>()

But then we’d need reified generics to access that type inside a function, and on the JVM reified generics are expensive…

Fortunately, Kotlin has inline functions, and they now support reified type parameters, so we can write something like this:

1

2

3

4

5

6

7

inline fun<reifiedT>TreeNode.findParentOfType():T?{

varp=parent

while(p!=null&&p!isT){

p=p?.parent

}

returnpasT

}

We qualified the type parameter with the reified modifier, now it’s accessible inside the function, almost as if it were a normal class. Since the function is inlined, no reflection is needed, normal operators like !is are working now. Also, we can call it as mentioned above: myTree.findParentOfType<MyTreeNodeType>().

Though reflection may not be needed in many cases, we can still use it with a reified type parameter: javaClass() gives us access to it:

1

2

3

4

5

inline fun methodsOf<reifiedT>()=javaClass<T>().getMethods()

fun main(s:Array<String>){

println(methodsOf<String>().joinToString("\n"))

}

Normal functions (not marked as inline) can not have reified parameters. A type that does not have a run-time representation (e.g. a non-reified type parameter or a fictitious type like Nothing) can not be used as an argument for a reified type parameter.

This feature is intended to simplify code in frameworks that traditionally rely on reflection, and our internal experiments show that it’s working well.

Checks for declaration-site variance

Kotlin has declaration-site variance from the very beginning, but the correspondent checks have been missing from the compiler for a long time. Now they are put in their place: the compiler complains if we declare a type parameter as in or out, but misuse it in the class body:

1

2

3

classC<outT>{

fun foo(t:T){}// ERROR

}

In this example, since T is declared as out (i.e. the class is covariant in T), we are not allowed to take it as a parameter to the foo() function, we can only return it.

Note that a private declaration is allowed to violate variance restrictions, for example:

1

2

3

classC<outT>(t:T){

privatevarfoo:T=t

}

Although foo‘s setter takes T as as an argument, and thus violates the out restriction on it, the compiler allows this and makes sure that only the same instance of C has access to foo. This means that the following function in C would not compile:

1

2

3

4

// inside the class C

privatefun copyTo(other:C<T>){

other.foo=foo// ERROR: Can not access foo in another instance of C

}

This is a breaking change: some code that compiled previously may break, but not fixing it is likely to result in run-time exceptions anyways, so the compiler errors will be of some value to you

Type inference supports use-site variance

Type argument inference has been improved to accommodate use-site variance more comfortably. Now you can call a generic function, e.g. reverseInPlace() on a projected type, such as Array<out Number>:

Varargs translated to projected arrays

Another breaking change comes in the form of a fix to a obscure, but sometimes ratherannoying issue: when we have a function that takes a vararg of String?, we really want to be able to pass an array of String to it, don’t we? Before M10 it was impossible, because vararg of T were compiled to Array<T>, now they are compiled to Array<out T>, and the following code works:

1

2

3

4

fun takeVararg(vararg strings:String?){...}

val strs=array("a","b","c")

takeVararg(*strs)

JavaScript improvements and changes

JavaScript gets an important update in this version with support for dynamic types.

Dynamic support

Sometimes the best way to talk to dynamic languages is dynamically. This is why we’ve introduced the soft keyword dynamic which allows us to declare types as dynamic. Currently this is only supported when targeting JavaScript, not the JVM.

When interoperating with JavaScript we can now have functions take as parameters, or return, a dynamic type

1

2

3

4

fun interopJS(obj:dynamic):dynamic{

...

return"any type"

}

We’ll cover dynamic in more details along with usage scenarios and limitations in a separate blog post. For technicalities see the spec document.

New Annotations

We’ve added a series of annotations to make JavaScript interop easier, in particular nativeInvoke, nativeGetter and nativeSetter.

If a function bar is annotated with nativeInvoke, its calls foo.bar() are translated to foo() in JavaScript. For example:

1

2

3

4

5

6

7

8

classFoo{

nativeInvoke

fun invoke(a:Int){}

}

valf=Foo()

f(1)// translates to f(1), not f.invoke(1)

f.invoke(1)// also translates to f(1)

Much the same way, we can use nativeGetter and nativeSetter to get index-access available in JavaScript:

1

2

3

4

5

6

7

native("Array")

classJsArray<T>{

nativeGetter

fun get(i:Int):T=noImpl

nativeSetter

fun set(i:Int,v:T):Unit=noImpl

}

Without native* annotations, calls to get and set (including those done by convention, e.g. a[i] = j is the same as a.set(i, j)) are translated to a.get(...) and a.set(...), but with the annotations placed as above, they are translated to square brackets operator in JavaScript:

1

2

3

a[0]// translates to a[0], not a.get(0)

a.get("first")// translates to a["first"]

a[2]=3// translates to a[2] = 3

We can use these annotations in the following cases:

non-extension member functions of native declarations,

top-level extension functions.

Kotlin.js output – breaking change

Previously, when creating a new project, the kotlin.js runtime would be created in a folder named scripts. As of M10, this file is created on first compilation and is placed in the output folder (defaults to out). This provides for a much easier deployment scenario as library and project output is now located under the same root folder.

New no-stdlib option to kotlin-js compiler – breaking change

We now provide a command line option for the kotlin-js compiler, namely no-stdlib. Without specifying this option, the compiler uses the bundled standard library. This is a change of behaviour from M9.

js code

We can now output JavaScript code directly inside Kotlin code

1

js("var value = document.getElementById('item')")

which takes the code provided as parameter and injects it directly into the AST JavaScript code that the compiler generates.

As you can see, we’ve added a lot of new improvements for JavaScript in this release and we’ll cover these in more detail in a separate post.

Java Interop

[platformStatic] for properties

Now, we can mark properties as [platformStatic] so that their accessors become visible from Java as static methods.

Static fields in objects

Properties on any object now produce static fields so that they can easily be consumed from Java even without the need to decorate them with platformStatic annotations.

IntelliJ IDEA improvements

Some more improvements in the IntelliJ IDEA area, including:

Incremental compilation in mixed projects

We’ve enhanced incremental compilation and with M10 it now supports dependencies between Kotlin and Java code. Now when you change your Java code, the relevant parts of your Kotlin code are re-compiled. As a reminder, incremental compilation is activated under the Kotlin Compiler options.

HotSwap fixed in debugger

Now, when we recompile Kotlin code while debugging it, it gets smoothly re-loaded into the debugee process.

Evaluate Expression: Completion improvements

During debug sessions, when evaluating expressions, casts are automatically added as needed. For instance when downcasting from Any to a specific type.

Copy reference

Create from usage for classes and packages

Create from usage is now available for classes and packages, which contributes significantly to a TDD workflow. Even if you’re not doing TDD, it does minimize friction of creating new elements.

Generics in change signature

The Change Signature refactoring now supports generics in cases where a base class function is promoted to use generics. In essence, in the following scenario

1

2

3

4

5

6

7

openclassBase<T>{

open fun baseMethod<K>(t:T,k:K){}

}

classDerived<X>:Base<List<X>>{

override fun baseMethod<Y>(a:List<X>,b:Y){}

}

If the signature of Base.baseMethod is changed to baseMethod<T>(t: List<T>, k: K?) then the signature of Derived.baseMethod is appropriately changed to >baseMethod<Y>(a: List<Y>, b: List<X>?)

Completion improvements

Completions items ordering has been improved, immediate members are now highlighted. Smart completion now finds inheritors of expected types. Completion performance severely improved.

Runnable objects

Now you can run an object that declared a [platformStatic] main function, for the IDE:

1

2

3

4

5

6

7

import kotlin.platform.*

objectHello{

platformStatic fun main(args:Array<String>){

println("Hello")

}

}

Just right-click the object and select Run …

Code Coverage highlighting in the Editor

If you run Kotlin code with coverage, the Editor now marks covered and uncovered lines for you (available in IntelliJ IDEA 14 only).

JavaScript project configuration

The IDE plugin can now automatically configure Maven projects to work with Kotlin/JS. Also, if you have an outdated version of Kotlin’s runtime library, the IDE will ask you to update it, and you can now chose to use a library located in the plugin distribution, instead of copying one into your project.

Summary

To install M10, update the plugin in your IntelliJ IDEA 14 (or earlier versions), and as always you can find the plugin in our plugin repository. You can also download the standalone compiler from the release page.

1. There used to be a handy constructor for Array – the one that took a size and a function that populates elements. Why was it deleted and what’s the way to construct a new array of given size, say, of type Array? Only creating it using arrayOfNulls, manually populating it and then casting it to be not nullable?
2. Why there are functions listOf(), arrayListOf() and so on, but corresponding function for arrays is array(), not arrayOf()?

In my eyes this would remove redundancy while improving readability. Plus it would make multiple tasks faster:
– Moving of initialized fields between constructor and class body
– Reordering arguments/parameters (no comma/no-comma switch for the last entry)
– Defining lists with long entries

It should still be easy for the brain/compiler to distinguish between blocks and argument/parameter lists because of the different types of parentheses. Ambiguities with entry separation should be rare and the problem was nicely solved for instructions inside blocks.

I’d say that this request is logical, but questionable, because, unlike statements, arguments are very often passed on a single line, and as code evolves, we migrate between two forms, thus the user (or a tool) would have to add/remove commas upon simple (and common) changes of formatting

I agree that this change is questionable. I still believe that it could result in a better language, mainly for the following reason: You read code much more often than you write it. That’s why all the tooling issues should not be weighted too heavy versus the improved readability caused by decreased comma noise.

Anyhow, here are my thoughts about the tooling: In my experience argument/parameter list are most readable if all entries are on a single line or all entries are on different lines. What about providing a refactoring tool that converts any of those lists into one of those well-readable forms? For calls, an option to name all parameters at the same time would be cool!

All cases would be well covered now:
– Converting multi-line to single-line: Deleting the line break between two entries automatically inserts a comma before the cursor. Better and faster approach: Use the refactoring above.
– Converting single-line to multi-line: Just use the refactoring above or: Inserting line breaks automatically removes redundant commas.
– Removing redundant multi-line commas in existing code: This could be be part of the reformatting.
– Writing a new single-line list: As before.
– Writing a new multi-line list: Easier than before because no commas have to be provided.

Independently: Thank you for making Kotlin! Combined with IntelliJ it is programmers dream. Keep up your great work.