apply carefully — Kotlin Java Interoperability

This post has been republished via RSS; it originally appeared at: Microsoft Mobile Engineering - Medium.

apply carefully — Kotlin Java Interoperability

Recently at Yammer, we discovered an issue with Kotlin’s apply scope function and Kotlin compiler’s inability to warn of self-assignment, when the receiver is a Java class.

Kotlin standard library contains several scoping functions that take a receiver argument and a block of code, and then execute the provided block of code within the context of that object.

What’s different is how this object becomes available inside the block and what is the result of the whole expression. Scope functions can make your code more concise and readable, but some subtle pitfalls await.

Consider a scenario, where you have a Java class, that represents an Attachment. Perhaps this is DAO class that is eventually saved to the database.

Assume that certain API returns an ImageFile that contains properties that can be represented by the following data class.

Now we wish to convert this ImageFile to Attachment. One could write an extension method that uses apply like this.

If you run the above code you will notice that Kotlin compiler/IDE is not able to warn you about self-assignment. ImageFile.toAttachment extension method will always create an Attachment object where updateTime is set at 1970/1/1.

Should the Kotlin compiler be able to detect self-assignment to updateTime? As of Kotlin 1.5.0, the IDE doesn’t generate this warning. We reported this issue to the JetBrains team, and it is tracked here.

If one creates a Kotlin data class, KotlinAttachment, and an extension method for ImageFile, that returns KotlinAttachment as shown below. The IDE will correctly generate a self-assignment warning.

If you find yourself in a similar situation where a receiver is a Java object, to be safe, prefer to use the Kotlin scope function also.

Thanks to my colleague Daniel Robertson, for suggesting a fix for the toAttachment extension method.

Now we can correctly update properties for the receiver, by explicitly referring to the object as it.

If you are interested in joining us, Yammer is expanding and looking to hire Android Engineers in Vancouver, BC!

- Senior Android Engineer: https://lnkd.in/gABtx85
- Android Engineer 2: https://lnkd.in/gth-yRr


apply carefully — Kotlin Java Interoperability was originally published in Microsoft Mobile Engineering on Medium, where people are continuing the conversation by highlighting and responding to this story.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.