Auto Added by WPeMatico

KotlinConf가 2023년 4월 암스테르담에서 다시 개최됩니다!

기쁘다는 말로는 부족한 소식이 있습니다. 바로 KotlinConf가 다시 개최된다는 매우 기대되고, 기쁨과 즐거움이 넘치는 소식입니다!

🌷 2023년 4월 12~14일에 암스테르담에서 KotlinConf 행사가 개최됩니다. 마침내 다시 한자리에 모여 Kotlin과 관련한 흥미로운 소식을 전해 드릴 수 있습니다!

올해의 행사에서 Kotlin 커뮤니티와 함께하려면 지금 등록하세요. 워크숍, 토크, fun이 함께합니다! 티켓이 매진되기 전에 구매하세요!

티켓 구매하기

워크숍 데이

워크숍 첫날인 2023년 4월 12일, KotlinConf가 시작됩니다. 각 워크숍에 인원 제한이 있으므로 워크숍에 참석하고 싶다면 바로 등록하세요.

컨퍼런스 패스와 함께 워크숍 참여권 1개를 구매할 수 있습니다. 아래의 내용을 확인하고 원하는 워크숍을 선택하세요.

Building Android Apps With Jetpack Compose(Jetpack Compose로 Android 앱 빌드하기) – Florina Muntenescu

이 워크숍을 통해 기초를 단단히 다지고 상태, 레이아웃, 디자인 시스템 및 애니메이션을 사용하는 선언형 사고 방식의 기초를 학습할 수 있습니다. 또한 뷰 기반 앱에서 Compose로의 실제 마이그레이션 과정을 살펴보고, Jetpack Compose에서 레이아웃의 작동 방식을 상세히 알아보며 워크숍을 마무리할 예정입니다.

Kotlin Multiplatform Mobile in Production(프로덕션 단계에서 Kotlin Multiplatform Mobile의 활용) – Kevin Galligan, Tadeas Kriz, Russell Wolf

이 워크숍에서는 빌드 시스템 및 도구 통합, iOS 측 SDK 디자인, 팀 구조, ‘Kotlin으로 개발하는 사람’ 등 Kotlin Multiplatform Mobile을 프로덕션에 적용하는 몇 가지 실습 중심의 예시를 살펴봅니다.

Kotlin TDD Masterclass(Kotlin TDD 마스터 클래스) – Nat Pryce, Duncan McGregor

테스트 주도 개발(TDD)과 관련한 실습 중심의 이 워크숍에서 TDD에 활용 가능한 Kotlin의 기능 및 TDD 방식이 Kotlin에 제공하는 이점을 살펴볼 예정입니다. 함수형 스타일이 테스트 및 디자인에 어떤 영향을 미칠까요? 모킹을 피할 수 있을까요? 과연 그렇게 하는 게 맞을까요? 테스트 중 타입 시스템의 역할은 무엇일까요? 워크숍을 통해 이와 같은 질문의 답을 함께 찾아보세요.

Building Scalable Microservices With Ktor and Kafka(Ktor 및 Kafka를 사용하여 확장 가능한 마이크로서비스 구축) – Anton Arhipov, Viktor Gamov

이 워크숍에서는 서버 측 개발을 위한 3가지 K(Kotlin 프로그래밍 언어, Ktor 서비스 프레임워크, 이벤트 스트리밍을 위한 Kafka)를 설명합니다. 워크숍을 마치면 다음과 같은 지식을 습득할 수 있습니다.

  • Ktor를 사용하여 유연한 RESTful 서비스를 만들고 배포하는 방법.
  • 추가 구성이 필요한 외부 라이브러리와 Ktor를 통합하는 방법.
  • Kafka 스트리밍과 같은 다양한 도구를 사용하여 서비스를 유연하게 연결하는 방법.

Asynchronous Programming With Kotlin Coroutines(Kotlin 코루틴을 사용한 비동기 프로그래밍) – Svetlana Isakova, Sebastian Aigner, Roman Elizarov

이 워크숍에서는 Kotlin 코루틴을 활용하여 생산성을 향상하는 데 필요한 모든 것을 학습합니다. 워크숍을 완료하면 코루틴 관련 용어를 익히고, 일반적 문제를 발견하고 예방하는 방법을 이해할 수 있습니다. 또한 프로젝트에서 코루틴을 효과적으로, 자신감 있게 사용할 수 있습니다.

Reactive Spring Boot With Coroutines(코루틴을 사용한 반응형 Spring Boot) – Urs Peter

이 워크숍에서는 Spring Boot의 코루틴 지원이 미흡한 Webflux 접근 방식의 모든 단점을 제거하고, 복잡하지 않게 반응형 기능을 제공하는 방식을 학습할 수 있습니다.

Kotlin Multiplatform 입문 – Romain Boisselle, Salomon Brys

이 워크숍을 통해 Jetpack Compose로 Android에서, Swift UI로 iOS, JetBrains Compose Web으로 웹에서, JetBrains Compose Desktop으로 데스크톱 JVM에서 실행되는 작은 애플리케이션을 개발합니다. 이러한 애플리케이션은 네이티브 룩앤필을 제공하고 완전히 테스트를 거쳐 일관성 있는 비즈니스 레이어를 재사용할 수 있습니다.

Kotlin을 사용한 함수형 프로그래밍 – Raúl Raja Martínez, Alejandro Serrano Mena, Simon Vergauwen

이 워크숍에서는 Kotlin 코드에 직접 적용 가능한 함수형 프로그래밍의 개념을 살펴봅니다. Arrow가 지원 라이브러리로 사용됩니다. 이 라이브러리는 함수형 스타일을 한층 잘 활용할 수 있도록 유용한 타입 및 확장자를 제공합니다.

KotlinConf 등록하기

발표자 모집

KotlinConf는 커뮤니티 이벤트로, 많은 분들의 참여를 기다립니다. 지금 발표자를 모집하고 있습니다!

발표 주제를 제출하고 여러분의 경험을 공유해 주세요. Kotlin을 사용한 혁신적인 방법, 여러분이 경험한 문제, 직접 제작한 프레임워크 또는 다른 사람에게 도움이 될 만한 정보라면 무엇이든 발표 주제가 될 수 있습니다.

발표 주제 제출하기


KotlinConf’23에 대한 자세한 내용을 알아보려면 kotlinconf.com을 방문하고 트위터에서 KotlinConf를 팔로우해 주세요.

게시물 원문 작성자

Ksenia Shneyveys

Continue ReadingKotlinConf가 2023년 4월 암스테르담에서 다시 개최됩니다!

KotlinConf 将于 2023 年 4 月在阿姆斯特丹回归!

KotlinConf 回来了! 我们很高兴宣布这个消息,实在是迫不期待了!

🌷 下一届 KotlinConf 将于 2023 年 4 月 12 日至 14 日在阿姆斯特丹线下举行。 我们终于可以再次聚在一起,分享 Kotlin 的精彩之处了。

立即注册,加入 Kotlin 社区的年度盛会。 将有研讨会、演讲,并且保证充满乐趣! 抓紧时间购买门票,以免售罄!

购买门票

研讨会日

我们将在 KotlinConf 的第一天(2023 年 4 月 12 日)举行研讨会。 每个研讨会的席位有限,因此如果您有兴趣参加,请尽快注册。

除了购买会议通行证之外,还可以购买研讨会门票。 选择您喜欢的研讨会

Building Android Apps with Jetpack Compose(使用 Jetpack Compose 构建 Android 应用),主持人:Florina Muntenescu

在这个研讨会中,您将从打下坚实的基础开始,学习声明式思维的基本原理,使用状态、布局、设计系统和动画。 然后,您将完成一个从基于视图的应用到 Compose 的实际迁移,最后深入了解布局在 Jetpack Compose 中的运作方式。

Kotlin Multiplatform Mobile in Production(在生产中使用 Kotlin Multiplatform Mobile),主持人:Kevin Galligan、Tadeas Kriz 和 Russell Wolf

在这个研讨会中,我们将通过一些动手示例,将 Kotlin Multiplatform Mobile 投入生产,包括构建系统和工具集成、iOS 端 SDK 设计、团队结构和“谁编写 Kotlin?”等。

Kotlin TDD Masterclass(Kotlin TDD 大师班),主持人:Nat Pryce 和 Duncan McGregor

在这个关于测试驱动型开发的动手研讨会上,我们将探讨 Kotlin 和 TDD 给彼此带来了什么。 函数式编程是如何影响测试和设计的? 我们能不能避免模拟,我们是否应该避免? 在有测试的情况下,类型系统扮演什么角色? 加入我们并找出答案!

Building Scalable Microservices With Ktor and Kafka(使用 Ktor 和 Kafka 构建可扩缩的微服务),主持人:Anton Arhipov 和 Viktor Gamov

在这个研讨会中,我们将介绍服务器端开发的三个 K:Kotlin 编程语言、Ktor 服务框架和用于事件流的 Kafka。 在研讨会结束时,您将了解:

  • 如何使用 Ktor 创建和部署弹性 RESTful 服务。
  • 如何将 Ktor 与需要额外配置的外部库集成。
  • 如何使用各种工具(如 Kafka 流)灵活地连接服务。

Asynchronous Programming With Kotlin Coroutines(使用 Kotlin 协同程序进行异步编程),主持人:Svetlana Isakova、Sebastian Aigner 和 Roman Elizarov

在这个研讨会中,您将学习在 Kotlin 中使用协同程序提高效率所需的一切。 研讨会结束时,您将增强自己的协同程序词汇,了解如何发现和避免常见问题,并能够在您自己的项目中有效且自信地使用协同程序。

Reactive Spring Boot With Coroutines(反应式 Spring Boot 与协同程序),主持人:Urs Peter

在这个研讨会中,您将了解 Spring Boot 的协同程序支持如何消除“原始”Webflux 方式的所有缺点,并为您提供毫不复杂的反应式特性。

Getting Started With Kotlin Multiplatform(Kotlin Multiplatform 使用入门),主持人:Romain Boisselle 和 Salomon Brys

在这个研讨会中,我们将构建一个小型应用程序:使用 Jetpack Compose 构建在 Android 上运行的变体,使用 Swift UI 构建在 iOS 上运行的变体,使用 JetBrains Compose Web 构建在网络上运行的变体,使用 JetBrains Compose Desktop 构建在桌面 JVM 上运行的变体,提供原生外观,同时重用一个经过充分测试的连贯业务层。

Functional Programming in Kotlin(Kotlin 中的函数式编程),主持人:Raúl Raja Martínez、Alejandro Serrano Mena 和 Simon Vergauwen

在这个研讨会中,我们将研究直接适用于 Kotlin 代码的函数式编程的概念。 我们将使用 Arrow 作为支持库,它包括许多有用的类型和扩展,能够使函数式编程体验更加愉悦。

预定席位

演讲嘉宾招募

KotlinConf 是一个社区活动,因此我们希望您能参加。论文征集现已开放!

提交演讲主题并分享您的经历,无论是寻找使用 Kotlin 的创新方式、您面临的挑战、您创建的框架,还是您想分享的任何可以帮助其他人的内容。

提交您的演讲主题


有关 KotlinConf’23 的更多信息,请访问 kotlinconf.com 并在 Twitter 上关注 KotlinConf

本博文英文原作者:

Ksenia Shneyveys

Continue ReadingKotlinConf 将于 2023 年 4 月在阿姆斯特丹回归!

KotlinConf returns to Amsterdam in April 2023!

We’re happy – no, strike that! – we’re thrilled, ecstatic, and overjoyed to announce that KotlinConf is back!

🌷 The next KotlinConf will take place in person in Amsterdam on April 12–14, 2023. Finally we’ll be able to get together again and share the exciting things going on with Kotlin. 

Register now to join the Kotlin community at the event of the year. Workshops, talks, and fun are guaranteed! Get your tickets before they run out!

Get tickets

Workshop Day

We’ll kick off KotlinConf with the first day of workshops – April 12, 2023. The seats for each workshop are limited, so please register soon if you are interested in attending. 

One workshop can be bought in addition to the conference pass. Choose your favorite:

Building Android Apps With Jetpack Compose, by Florina Muntenescu

In this workshop, you’ll start by building a solid foundation and learn the fundamentals of declarative thinking, working with states, layouts, design systems, and animation. You’ll then walk through a practical migration of a View-based app to Compose, and finish by diving deeper into how layouts work in Jetpack Compose.

Kotlin Multiplatform Mobile in Production, by Kevin Galligan, Tadeas Kriz, and Russell Wolf

In this workshop, we’ll work through some hands-on examples of putting Kotlin Multiplatform Mobile into production, including build system and tooling integration, iOS-side SDK design, team structure and “Who writes Kotlin?”, and more.

Kotlin TDD Masterclass, by Nat Pryce and Duncan McGregor

In this hands-on Test Driven Development workshop, we’ll explore what Kotlin brings to TDD, and what TDD brings to Kotlin. How does a functional style affect testing and design? Can we avoid mocking, and should we? What role does the type system play when we have tests? Join us and find out.

Building Scalable Microservices With Ktor and Kafka, by Anton Arhipov and Viktor Gamov

In this workshop, we will cover the three Ks for server-side development: the Kotlin programming language, the Ktor services framework, and Kafka for event streaming. By the end of the workshop you will know:

  • How to create and deploy resilient RESTful services using Ktor.
  • How to integrate Ktor with external libraries that require additional configuration.
  • How to flexibly connect services using a variety of tools, such as Kafka streams.

Asynchronous Programming With Kotlin Coroutines, by Svetlana Isakova, Sebastian Aigner, and Roman Elizarov

In this workshop, you’ll learn everything you need to become productive with coroutines in Kotlin. By the end, you’ll have enhanced your coroutines-related vocabulary, understand how to spot and avoid common problems, and will be able to effectively and confidently use coroutines in your own projects.

Reactive Spring Boot With Coroutines, by Urs Peter

In this workshop, you’ll learn how Spring Boot’s Coroutine support wipes out all of the downsides of the ‘raw’ Webflux approach and provides you with reactive characteristics without the complexity.

Getting Started With Kotlin Multiplatform, by Romain Boisselle and Salomon Brys

In this workshop, we’ll be building a small application that runs on Android with Jetpack Compose, on iOS with Swift UI, on the web with JetBrains Compose Web, and on desktop JVMs with JetBrains Compose Desktop, providing a native look and feel while reusing a fully tested and coherent business layer. 

Functional Programming in Kotlin, by Raúl Raja Martínez, Alejandro Serrano Mena, and Simon Vergauwen

In this workshop, we’ll look at concepts from functional programming that are directly applicable to Kotlin code. We’ll use Arrow as a supporting library, which includes many useful types and extensions to make a functional style even more pleasant.

Secure your spot

Call for speakers

KotlinConf is a community event, so we would love for you to take part. The call for papers is now open!

Submit a talk and share your experience, whether it’s about finding innovative ways to use Kotlin, the challenges you’ve faced, a framework you’ve created, or anything you’d like to share that could help others along their journey.

Submit your talk


For more information on KotlinConf’23, be sure to visit kotlinconf.com and follow KotlinConf on Twitter.

Continue ReadingKotlinConf returns to Amsterdam in April 2023!

Kotlin 1.7.0 Released

Kotlin 1.7.0 has been released. It unveils the Alpha version of the new Kotlin/JVM K2 compiler, stabilizes language features, and brings performance improvements for the JVM, JS, and Native platforms.

Here is a list of the major updates in this version:

Read the complete list of changes in What’s new in Kotlin 1.7.0.


How to install Kotlin 1.7.0

If you already use IntelliJ IDEA or Android Studio Chipmunk (212), your IDE will suggest updating Kotlin to 1.7.0 automatically. You can also update manually for these IDEs by following these instructions.

For Intellij IDEA 2022.2, and Android Studio Dolphin (213) or Android Studio Electric Eel (221), the Kotlin plugin 1.7.0 will be delivered with upcoming Intellij IDEA and Android Studios updates.

Make sure that you have also updated the kotlinx libraries to compatible versions and specified version 1.7.0 of Kotlin in the build scripts of your existing projects.

If you need the command-line compiler, download it from the GitHub release page.

If you run into any problems

Stay up to date with the latest Kotlin features! Subscribe to receive Kotlin updates by filling out the form to the right of this post.

What else to read and watch

Top issue reporters from YouTrack 

Philip Wedemann (28 issues), AndroidDeveloperLB (20 issues), Morgan Bartholomew (12 issues), meng wang (10 issues), Carlos Ballesteros Velasco (10 issues), Ivan Gavrilovic (9 issues), Steven Schäfer (9 issues), Tianyi Guan (9 issues), Niklas Baudy (9 issues), holger brandl (9 issues), Mike Hearn (8 issues), Eliezer Graber (8 issues), Waldemar Kornewald (8 issues), Piotr Krzemiński (8 issues), Yigit Boyar (7 issues), Javier Segovia Córdoba (7 issues), Oliver O. (7 issues), vivek modi (7 issues), Philip Dukhov (7 issues).

External contributors

We’d like to thank all of our contributors whose pull requests were included in this release: Jinseong Jeon, Tianyu Geng, pyos, Hung Nguyen, Mark Punzalan, Mads Ager, Steven Schäfer, Irene Dea, Ivan Gavrilovic, Xin Wang, Kristoffer Andersen, wrongwrong, Mattia Iavarone, Martin Petrov, Aurimas, Alexey Subach, Udi Cohen, Quantum64, Dario Seidl, David Saff, Denis Mekhanikov, Egor, Glen K. Peterson, Ian Lynagh, Iaroslav Postovalov, Jerome Prinet, Jiaxiang Chen, Joseph Walton, Kevin Bierhoff, Matthew Haughton, Michael Rittmeister, Morten Krogh-Jespersen, Nikolay Kasyanov, Piotr Krzeminski, 770grappenmaker, Rick Clephas, Ryan Nett, Shumaf Lovpache, Starlight220, Yigit Boyar, Zac Sweers, aragos, baratynskiy, ov7a, sgmoore, soywiz, tdn120.

Continue ReadingKotlin 1.7.0 Released

Kotlin 1.6.0 veröffentlicht

Kotlin 1.6.0 ist jetzt offiziell veröffentlicht – mit Stable-Status für abschließende when-Blöcke, dem Code-Coverage-Tool Kover und einem neuen Speichermanager für Kotlin/Native. Auch andere Neuerungen in der Sprache und den Standardbibliotheken, die in 1.5.30 veröffentlicht wurden, wurden in den Status Stable befördert. Vielen Dank für das Feedback, das Sie uns zukommen ließen. Wenn Sie diese neuen Features noch nicht ausprobiert haben – jetzt ist es höchste Zeit!

In diesem Blogbeitrag finden Sie einen Überblick über die folgenden Updates:

  • Neue Sprachmerkmale: versiegelte when-Anweisungen, suspendierende Funktionen und entsprechende Umwandlungen, Instanziierung von Annotationsklassen, verbesserte Typinferenz für reguläre und Builder-Typen.
  • Kotlin/JVM mit optimierten delegierten Eigenschaften und wiederholbaren Annotationen.
  • Kotlin/Native mit der Preview eines neuen Speichermodells, Xcode-13-Unterstützung, Kreuzkompilierung von Windows-Zielen, LLVM- und Linker-Updates, Leistungsupdates und einer einheitlichen Compiler-Plugin-ABI.
  • Optionale Deaktivierung des Herunterladens von Node.js und Yarn für Kotlin/JS.
  • Ankündigung von Kover.
  • Standardbibliothek mit neuen Funktionen für die Standardeingabe, stabiler typeOf()-Funktion, stabiler Duration-API und weiteren stabilen stdlib-Funktionen.

Abonnieren Sie unser Blog, um keine Kotlin-Updates zu verpassen!

So führen Sie das Update durch

Wenn Sie IntelliJ IDEA oder Android Studio verwenden, haben Sie die Möglichkeit, automatisch auf die neue Kotlin-Version zu aktualisieren.

Weitere Informationen zur Installation von Kotlin 1.6.0.

Auf Kotlin 1.6.0 aktualisieren

Sprachmerkmale

Wir haben Sprachmerkmale aus Kotlin 1.5.30 basierend auf Ihrem Feedback stabilisiert.

Abschließende (versiegelte) when-Anweisungen

Versiegeltes when ist eine lang erwartete Funktion des Kotlin-Compilers, die Sie warnt, wenn Ihre when-Anweisungen nicht abschließend sind, also nicht alle Möglichkeiten berücksichtigen. Dadurch wird Ihr Code sicherer, ohne eigene Funktionen für diesen Zweck schreiben zu müssen. 

Kotlin hat when-Ausdrücke, die sich auf versiegelte Klassen, Enums und boolesche Typen bezogen, schon immer auf Vollständigkeit überprüft. Dies ist nützlich, wenn Sie Ihre Domäne mit diesen algebraischen Datentypen abbilden. Sie könnten beispielsweise in Ihrer App unterschiedliche Kontaktpräferenzen der Benutzer*innen als versiegelte Klassenhierarchie modellieren:

sealed class Contact {
   data class PhoneCall(val number: String) : Contact()
   data class TextMessage(val number: String) : Contact()
   data class InstantMessage(val type: IMType, val user: String) : Contact()
}

Wenn Sie nun einen Ausdruck schreiben, der abhängig von der Kontakteinstellung ein unterschiedliches Ergebnis zurückgibt, meldet der Compiler einen Fehler, wenn Sie vergessen haben, alle Typen zu berücksichtigen, die in Ihrer App möglich sind:

fun Rates.computeMessageCost(contact: Contact): Cost =
   when (contact) { // ERROR: 'when' expression must be exhaustive
       is Contact.PhoneCall -> phoneCallCost
       is Contact.TextMessage -> textMessageCost
   }

Dies ist eine große Hilfe sowohl beim Schreiben des Codes als auch bei der späteren Wartung. Wenn Sie später eine weitere Kontaktoption hinzufügen, können Sie sich darauf verlassen, dass der Compiler Sie daran erinnert, die verschiedenen Kontaktpräferenzen überall in Ihrem Code zu berücksichtigen.

Vor Kotlin 1.6 wurde jedoch die when-Anweisung im folgenden Code erfolgreich kompiliert, obwohl versäumt wurde, den Versand einer Nachricht per Instant Messaging zu implementieren:

fun sendAnnouncement(contact: Contact, announcement: Announcement) {
   when (contact) {
       is Contact.PhoneCall -> schedulePhoneCall(contact.number, announcement)
       is Contact.TextMessage -> sendTextMessage(contact.number, announcement)
   }
}

Das Problem wurde nur von einer nachrangigen IDE-Inspektion gemeldet, ohne irgendwelche Meldungen vom Compiler. Ab Kotlin 1.6 wird die folgende Compiler-Warnung ausgegeben:

Non-exhaustive 'when' statements on sealed class/interface will be prohibited in 1.7. Add an 'is InstantMessage' branch or 'else' branch instead.

In Kotlin 1.7 wird dies als Fehler gewertet, damit solche Fälle nicht übersehen werden können. Im Ticket KT-47709 finden Sie eine genauere Erläuterung der Änderung und ihrer Auswirkungen. 

Suspendierende Funktionen als Supertypen

Kotlin 1.6 stabilisiert die Unterstützung für die Implementierung von suspend-Funktionstypen als Superschnittstellen. Dies war eines der fehlenden Puzzleteile beim Design der Kotlin-Coroutinen. 

Bei der Gestaltung von Kotlin-APIs ist es idiomatisch, Funktionstypen zu akzeptieren, wenn das Verhalten von Bibliotheksfunktionen anpassbar sein soll. Beispielsweise verfügt die Schnittstelle Job der API kotlinx.coroutines über eine Memberfunktion, die ungefähr so aussieht:

fun invokeOnCompletion(handler: () -> Unit)

Sie können diese Funktion bequem mit Lambdas wie nachAbschlussAufrufen { etwasTun() } verwenden. Wenn Sie eine Klasse haben, die auf den Abschluss reagieren soll, können Sie Ihren Code vereinfachen und optimieren, indem Sie den Funktionstyp () -> Unit direkt in Ihrer Klasse implementieren, sodass Sie keine zusätzliche Lambdafunktion benötigen:

class MyCompletionHandler : () -> Unit {
   override fun invoke() { doSomething() }
}

Ab Kotlin 1.6 ist diese Optimierung mit suspendierenden Funktionen möglich. Nehmen wir an, Ihre API akzeptiert suspendierende Funktionstypen wie diese:

public fun launchOnClick(action: suspend () -> Unit) {}

In diesem Fall sind Sie nicht mehr darauf beschränkt, Lambdas und Referenzen auf suspendierende Funktionen an diesen Code zu übergeben. Sie können die entsprechenden suspendierenden Funktionstypen auch in einer Klasse implementieren:

class MyClickAction : suspend () -> Unit {
   override suspend fun invoke() { doSomething() }
}

Umwandlungen in suspendierende Typen

Kotlin 1.6 befördert die Umwandlungen von regulären zu suspendierenden Funktionstypen in den stabilen Status. Wenn bei einem Parameter ein suspendierender Typ erwartet wird, können Sie jetzt einen geeigneten regulären Funktionstyp übergeben. Der Compiler führt die Umwandlung automatisch durch.

Dadurch wird eine kleine, aber störende Inkonsistenz beim Zusammenspiel zwischen regulären und suspendierenden Funktionen in Kotlin behoben. Wenn Sie eine Funktion höherer Ordnung haben, die eine suspendierende Funktion akzeptiert (Beispiel: ein collect-Aufruf auf einem Kotlin-Flow), müssen Sie zum Aufrufen nicht unbedingt ein Lambda wie im folgenden Code verwenden:

flow.collect { processItem(it) }
fun processItem(item: Item) { /* ... */ }

Stattdessen könnte es praktischer sein, eine Referenz auf die Funktion processItem an den collect-Aufruf zu übergeben – die Wirkung ist identisch.

flow.collect(::processItem)

Sie könnten dann eine Referenz auf Ihre Verarbeitungsfunktion in eine Variable extrahieren, um das Verhalten in Ihrem Code entsprechend anzupassen. Allerdings funktionierte dies in den Kotlin-Versionen vor 1.6 nicht. Dies liegt daran, dass Sie eine reguläre Funktion als Parameter übergeben, wo ein suspendierender Typ erwartet wird:

val processingFunction = ::processItem
flow.collect(processingFunction) // ERROR: Type mismatch

Der obige Code wird in Kotlin 1.6 einwandfrei kompiliert und funktioniert auch wie erwartet.

Verbesserte Typinferenz für rekursive generische Typen

Ab 1.6.0 kann der Kotlin-Compiler standardmäßig ein Typargument basierend nur auf den oberen Grenzen des entsprechenden Typparameters ableiten, wenn dieser ein rekursiver generischer Typ ist. Dies ermöglicht verschiedene Patterns mit rekursiven generischen Typen, die in Java häufig für Builder-APIs verwendet werden.

// Vor 1.5.30
val containerA = PostgreSQLContainer<nothing>(DockerImageName.parse("postgres:13-alpine")).apply {
    withDatabaseName("db")
    withUsername("user")
    withPassword("password")
    withInitScript("sql/schema.sql")
}

// Mit Compileroption in 1.5.30 oder standardmäßig ab 1.6.0
val containerB = PostgreSQLContainer(DockerImageName.parse("postgres:13-alpine"))
    .withDatabaseName("db")
    .withUsername("user")
    .withPassword("password")
    .withInitScript("sql/schema.sql")

Verbesserte Builder-Inferenz

In Kotlin 1.5.30 wurde die Compileroption -Xunrestricted-builder-inference eingeführt, um innerhalb von Builder-Lambdas auf Typinformationen über einen Builder-Aufruf zugreifen zu können. Konkret bedeutet dies die Möglichkeit, Aufrufe zu tätigen, die eine Instanz eines noch nicht bekannten Typs zurückgeben, z. B. get() in einem buildList()-Lambda.

Ab 1.6.0 müssen Sie nicht die Option -Xunrestricted-builder-inference angeben, um diese bisher unzulässigen Aufrufe zu tätigen. Mit der Compileroption -Xenable-builder-inference können Sie jetzt ohne Verwendung der Annotation @BuilderInference Ihre eigenen generischen Builder schreiben und Builder-Inferenzen automatisch aktivieren, wenn die reguläre Typinferenz keine Typinformationen ergibt.

Längere Unterstützung früherer API-Versionen

Ab Kotlin 1.6.0 können Sie bei der Entwicklung außer der aktuellen stabilen API-Version drei frühere Versionen (anstelle der bisherigen zwei) verwenden. Derzeit stehen Ihnen also die API-Versionen 1.3, 1.4, 1.5 und 1.6 zur Verfügung.

Kotlin/JVM

Wiederholbare Annotationen mit Laufzeiterhaltung. Wie Java 8 kennt auch Kotlin wiederholbare Annotationen. Ab Kotlin 1.6 ist diese Funktion Java-kompatibel. @kotlin.annotation.Repeatable akzeptiert jetzt jede Retention-Angabe und macht die Annotation sowohl in Kotlin als auch in Java wiederholbar. Außerdem werden wiederholbare Java-Annotationen jetzt auch auf Kotlin-Seite unterstützt.

Kotlin/Native

Ab sofort können Sie die experimentelle Version des neuen Kotlin/Native-Speichermanagers ausprobieren. Mit diesem Feature kommen wir unserem Ziel einer konsistenten Entwicklererfahrung bei Multiplattform-Projekten näher. Der neue Speichermanager hebt die bestehenden Beschränkungen für die gemeinsame Objektnutzung zwischen Threads auf und bietet Primitive für die nebenläufige Programmierung, die sicher sind, Lecks vermeiden und keine spezielle Verwaltung oder Annotationen von Seiten des Entwicklungsteams erfordern.

Sie können Xcode unbesorgt aktualisieren und an Ihren Kotlin-Projekten weiterarbeiten, da Kotlin/Native jetzt Xcode 13 unterstützt. 

Kompilieren von Windows-Zielen auf beliebigen Hosts. Sie können die Windows-Ziele mingwX64 und mingwX86 auf jedem Host kompilieren, der Kotlin/Native unterstützt.

Wir haben die LLVM-Abhängigkeit, die Kotlin/Native unter der Haube verwendet, überarbeitet. Neben einer auf 11.1.0 aktualisierten LLVM-Version und einer verringerten Größe der Abhängigkeiten bietet dies einige weitere Vorteile.

Vereinheitlichung der Compiler-Plugin-ABI mit den JVM- und JS-IR-Backends. Jetzt kann das Gradle-Plugin für Kotlin Multiplatform das einbettbare Compiler-Jar, das für die JVM- und JS-IR-Backends verwendet wird, auch für Kotlin/Native verwenden. Sie können jetzt dieselben Compiler-Plugin-Artefakte für die Native-Plattform und andere unterstützte Plattformen verwenden.

Kotlin/JS

Für Buildvorgänge auf einem Server ohne Internetverbindung können Sie jetzt das Herunterladen von Node.js und Yarn für Kotlin/JS-Projekte deaktivieren und die auf dem Host vorinstallierten Instanzen verwenden.

Kover

Die genaue Ermittlung der Code-Coverage war vom ersten Kotlin-Release an eine Herausforderung. Einige großartige Tools wie JaCoCo verarbeiten Kotlin-Code, sind jedoch nicht vollständig in unsere Gradle-Toolchain und unsere Multiplattform-Projekte integriert. In dieser Kotlin-Version haben wir begonnen, dieses Problem anzupacken. Unser neues Gradle-Plugin Kover ermittelt die Code-Coverage von Kotlin-Code, der mit dem Kotlin/JVM-Compiler kompiliert wurde. Das Tool befindet es sich in einer frühen Entwicklungsphase und gilt als experimentell – wir freuen uns auf Ihr Feedback in GitHub.

Sehen Sie sich das Kover-Video an, um mehr zu erfahren.

Standardbibliothek

Kotlin 1.6.0 schließt drei Einträge auf der stdlib-Roadmap: kein !! nach readLine(), stabiler Status für typeOf() und eine stabile Duration-API. Außerdem erhalten die folgenden stdlib-Elemente den Status Stable:

  • Collection-Builder
  • Bit-Rotation bei Ganzzahlen
  • Regex-Funktion zum Aufteilen von Zeichenfolgen in Sequenzen

Außerdem können Sie jetzt compareTo mit Infixnotation verwenden, und wir haben an der Konsistenz zwischen den replace()-Funktionen in JVM und JS gearbeitet.

Neue Funktionen für die Standardeingabe

In Kotlin 1.6.0 ist der Nicht-Null-Assertion-Operator !! nach dem Lesen einer Zeile von der Standardeingabe nicht mehr erforderlich. Dies vereinfacht den Einstieg für Neulinge und erleichtert das Unterrichten von Kotlin.

Wir bieten die folgenden neuen Möglichkeiten für das Lesen von der Konsole:

  • readln() löst eine Ausnahme aus, wenn das Dateiende erreicht wurde. Sie können diese Funktion verwenden, statt das Ergebnis von readLine() mit dem Operator !! auf null zu überprüfen.
  • Die neue Funktion readlnOrNull() ist eine Alternative, die null zurückgibt. Sie verhält sich also wie bisher readLine() – nur dass die Funktion jetzt einen passenderen Namen hat.

Diese Funktionen sind für JVM und Native verfügbar. Sie sind analog zu println() benannt – für Neueinsteiger*innen ist dies besonders hilfreich.

fun main() {
    println("Input two integer numbers each on a separate line")
    val num1 = readln().toInt()
    val num2 = readln().toInt()
    println("The sum of $num1 and $num2 is ${num1 + num2}")
}

Stabile Duration-API

Mithilfe Ihres Feedbacks haben wir die API für Zeiträume stabilisiert und den entsprechenden Roadmap-Eintrag geschlossen.

Neben einer besser lesbaren Ausgabe von Duration.toString() und neuen Funktionen zum Parsen von Durations aus Strings, die in 1.5.30 als Preview verfügbar waren, hat die Duration-API folgende Änderungen erfahren:

  • Die days-Komponente der Funktion toComponents ist jetzt vom Typ Long statt Int, um das Abschneiden von Werten zu vermeiden.
  • Die Enum DurationUnit ist kein Typalias mehr. Es gibt keine Fälle, in denen es als Typalias für Java.util.concurrent.TimeUnit in der JVM verwendet wird.
  • Als Wunsch der Community sind Erweiterungseigenschaften wie Int.seconds wieder da. Um ihre Anwendbarkeit einzuschränken, sind sie nur im Companion-Objekt der Klasse Duration verfügbar.
import kotlin.time.Duration.Companion.seconds

fun main() {
//sampleStart
    val duration = 5000.seconds
    println("There are ${duration.inWholeMinutes} minutes in ${duration.inWholeHours} hours")
//sampleEnd
}

Stabiles typeOf()

In Kotlin 1.6.0 hat typeOf() den Status Stable. Der entsprechende Roadmap-Eintrag wurde geschlossen. Seit 1.3.40 war typeOf() auf der JVM-Plattform als experimentelle API verfügbar. Jetzt ist die Funktion auf jeder Kotlin-Plattform verfügbar und gibt einen beliebigen Kotlin-Typ, den der Compiler ableiten kann, als KType zurück. 

inline fun <reified T> renderType(): String {
    val type = typeOf<T>()
    return type.toString()
}

fun main() {
    val fromExplicitType = typeOf<Int>()
    val fromReifiedType = renderType<List<Int>>()
}

Stabile Collection-Builder

Kotlin 1.6.0 befördert Collection-Builder-Funktionen wie buildMap(), buildList() und buildSet() in den Stable-Status. Von den Buildern zurückgegebene Collections sind jetzt im schreibgeschützten Zustand serialisierbar.

Stabile Bitrotation für Ganzzahlen

Die Funktionen rotateLeft() und rotateRight(), die die binäre Darstellung einer Zahl um die angegebene Anzahl von Bits nach links oder rechts rotieren, haben ab Kotlin 1.6.0 den Status Stable.

fun main() {
//sampleStart
    val number: Short = 0b10001
    println(number.rotateRight(2).toString(radix = 2)) // 100000000000100
    println(number.rotateLeft(2).toString(radix = 2))  // 1000100
//sampleEnd
}

Stabile Regex-Funktion zum Aufteilen von Zeichenfolgen in Sequenzen

Eine weitere seit Kotlin 1.6.0 stabile Funktion ist splitToSequence() zum Aufteilen einer Zeichenfolge in eine Sequenz mithilfe eines regulären Ausdrucks.

fun main(){
//sampleStart
    val colorsText = "green, red , brown&blue, orange, pink&green"
    val regex = "[,\s]+".toRegex()
    val mixedColor = regex.splitToSequence(colorsText)
        .onEach { println(it) }
        .firstOrNull { it.contains('&') }
    println(mixedColor) // "brown&blue"
//sampleEnd
}

CompareTo in Infixnotation

Die Funktion Comparable.compareTo zum Vergleichen von zwei Objekten kann jetzt in Infixnotation aufgerufen werden: 

class WrappedText(val text: String) : Comparable<WrappedText> {
    override fun compareTo(other: WrappedText): Int =
        this.text compareTo other.text
}

Einheitlichkeit zwischen JVM und JS bei replace() und replaceFirst()

Vor Kotlin 1.6.0 verhielten sich die Regex-Funktionen replace() und replaceFirst() auf JVM und JS unterschiedlich, wenn die Ersetzungszeichenfolge eine Gruppenreferenz enthielt. Das Verhalten von Kotlin/JS wurde an das Verhalten der JVM angepasst.

Kompatibilität

Wie bei allen Feature-Releases werden mit Kotlin 1.6.0 einige Deprecation-Zyklen für zuvor angekündigte Änderungen abgeschlossen. Alle diese Fälle wurden vom Sprachkomitee sorgfältig geprüft und sind im Kompatibilitätsleitfaden für Kotlin 1.6 aufgeführt. Sie können diese Änderungen auch in YouTrack einsehen.

Installation von Kotlin 1.6.0

Wenn Sie IntelliJ IDEA oder Android Studio verwenden, schlägt Ihnen die IDE automatisch die Aktualisierung auf Kotlin 1.6.0 vor. Alternativ ist auch eine manuelle Aktualisierung gemäß dieser Anleitung möglich.

Sie können die neuesten Versionen dieser IDEs herunterladen, um eine umfassende Kotlin-Unterstützung zu erhalten:

  • IntelliJ IDEA – zur Entwicklung von Kotlin-Anwendungen für verschiedene Plattformen.
  • Android Studio – zur Entwicklung von Android-Apps und plattformübergreifenden Mobilanwendungen.

Achten Sie darauf, auch die kotlinx-Bibliotheken auf die kompatiblen Versionen zu aktualisieren und die Kotlin-Version 1.6.0 in den Build-Skripten Ihrer bestehenden Projekte anzugeben.

Den Befehlszeilen-Compiler können Sie bei Bedarf von der GitHub-Release-Seite herunterladen.

Hilfe bei Problemen:

Bleiben Sie stets auf dem neuesten Stand der Kotlin-Entwicklung! Abonnieren Sie unsere Kotlin-Updates, indem Sie das Formular rechts neben diesem Beitrag ausfüllen.

Weitere Informationen zum Lesen und Ansehen

Liste der aktivsten Ticketersteller in YouTrack 

Ryan Nett (48 Tickets), Zac Sweers (22 Tickets), Tianyu Geng (18 Tickets), zhelenskiy (18 Tickets), Thodoris Sotiropoulos (15 Tickets), AndroidDeveloperLB (14 Tickets), Morgan, Bartholomew (14 Tickets), Mikhail Naftal (14 Tickets), Louis CAD (12 Tickets), Philip Wedemann (12 Tickets), Victor Turansky (11 Tickets), Igor Wojda (11 Tickets), Martin Bonnin (11 Tickets), Iaroslav Postovalov (11 Tickets), Cedric (10 Tickets), (9 Tickets), Ben Woodworth (8 Tickets), Tianyi Guan (8 Tickets), Chris Povirk (8 Tickets), Alon Albert (8 Tickets).

Externe Mitwirkende

Wir bedanken uns bei allen Mitwirkenden, die Pull-Requests zu dieser Version beigetragen haben: Pyos, Tianyu Geng, Jinseong Jeon, Steven Schäfer, Mark Punzalan, Hung Nguyen, Mads Ager, Ting-Yuan Huang, Matthew Gharrity, Ivan Gavrilovic, Xin Wang, ov7a, Jiaxiang Chen, Yigit Boyar, Bingran, bracadabra, Steffi Stumpos, Andrey Kuleshov.

Autorin des Original-Blogposts:

Sergiy Rogalin

Alina Grebenkina

Continue ReadingKotlin 1.6.0 veröffentlicht

Kotlin 1.6.0 Released

Kotlin 1.6.0 is now officially released with Stable exhaustive whens, Kover, and a new memory manager for Kotlin/Native. Other language and standard library features released in 1.5.30 became Stable as well. Thanks for the feedback you’ve shared with us. If you still haven’t tried these new features out, now is the time!

In this blog post, you can find an overview of the following updates:

  • Language features with sealed when statements, suspending functions and suspend conversions, instantiation of annotation classes, improved regular type inference and builder type inference.
  • Kotlin/JVM with optimized delegated properties and repeatable annotations.
  • Kotlin/Native with a preview of a new memory model, Xcode 13 support, a cross-compilation of Windows targets, LLVM and linker updates, performance updates, and unified compiler plugin ABI.
  • Option to disable downloading of Node.js and Yarn for Kotlin/JS.
  • Kover announcement.
  • Standard library with new functions for standard input, Stable typeOf(), Stable Duration API, and other stabilized stdlib functions.

Subscribe to our blog and don’t miss out on any Kotlin updates

How to update

If you use IntelliJ IDEA or Android Studio, you have the option to automatically update to the new Kotlin release as soon as it becomes available.

Learn more about installing Kotlin 1.6.0.

Update to Kotlin 1.6.0

Language features

We stabilized features from Kotlin 1.5.30 based on your feedback.

Sealed (exhaustive) when statements

Sealed when is a long-awaited feature that makes the Kotlin compiler warn you if your when statements are not exhaustive. This makes your code safer without having to introduce your own functions. 

Kotlin has always been exhaustive in checking when expressions for sealed classes, enums, and Boolean types. It is useful when you model your domain with those algebraic data types. For example, you might have different contract preferences for users of your app modeled as a sealed class hierarchy:

sealed class Contact {
   data class PhoneCall(val number: String) : Contact()
   data class TextMessage(val number: String) : Contact()
   data class InstantMessage(val type: IMType, val user: String) : Contact()
}

Now, if you write an expression that returns a different result based on different contact preference, the compiler will flag an error if you forget to handle all of the types you have in your app:

fun Rates.computeMessageCost(contact: Contact): Cost =
   when (contact) { // ERROR: 'when' expression must be exhaustive
       is Contact.PhoneCall -> phoneCallCost
       is Contact.TextMessage -> textMessageCost
   }

This is a great help, both in writing code and for future maintenance. If you add a different type of contact preference later, you know that the compiler will make sure you have not forgotten to handle the different types of contact preferences all around your code.

However, before Kotlin 1.6, the following code that uses when statements successfully compiles, even though it totally forgets to handle sending an announcement to your users via instant message:

fun sendAnnouncement(contact: Contact, announcement: Announcement) {
   when (contact) {
       is Contact.PhoneCall -> schedulePhoneCall(contact.number, announcement)
       is Contact.TextMessage -> sendTextMessage(contact.number, announcement)
   }
}

Only a weak IDE inspection was reported, without any messages from the compiler. Starting from Kotlin 1.6, it produces the following compiler warning:

Non-exhaustive 'when' statements on sealed class/interface will be prohibited in 1.7. Add an 'is InstantMessage' branch or 'else' branch instead.

In Kotlin 1.7 it will become an error, leaving no chance to accidentally forget it. Please see KT-47709 for a more detailed explanation of the change and its effects. 

Suspending functions as supertypes

Kotlin 1.6 stabilizes support for implementing suspend functional types as super interfaces. It was one of the missing pieces in the Kotlin coroutines design. 

When you design Kotlin APIs, it is idiomatic to accept functional types when you need to customize the behavior of various library functions. For example, kotlinx.coroutines API has a member function in its Job interface that looks similar to this:

fun invokeOnCompletion(handler: () -> Unit)

You can conveniently use this function with lambdas like invokeOnCompletion { doSomething() }. If you have a class that you wanted to handle the completion with, you can streamline and optimize your code by implementing the functional type () -> Unit directly in your class without creating an additional lambda:

class MyCompletionHandler : () -> Unit {
   override fun invoke() { doSomething() }
}

Starting from Kotlin 1.6 this optimization is possible with suspending functions. If your APIs accept suspending functional types, like this:

public fun launchOnClick(action: suspend () -> Unit) {}

… then you are not limited to passing lambdas and suspending function references to this code anymore. You can implement the corresponding suspending functional types in a class, too:

class MyClickAction : suspend () -> Unit {
   override suspend fun invoke() { doSomething() }
}

Suspend conversions

Kotlin 1.6 stabilizes conversions from regular to suspending functional types. You can now pass any expression of a suitable regular functional type where suspending is expected as a parameter. The compiler will perform a conversion automatically.

This fixes a small but annoying inconsistency in the interaction between regular and suspending functions in Kotlin. In you have a higher-order function that accepts a suspending function, like a collect call on a Kotlin Flow, then instead of using a lambda to call it, like this:

flow.collect { processItem(it) }
fun processItem(item: Item) { /* ... */ }

… you might find it convenient to pass a reference to the processItem function to the collect call to the same effect:

flow.collect(::processItem)

You would then extract a reference to your processing function into a variable in order to customize the behavior in your code. However, that didn’t work in Kotlin versions prior to 1.6. This is because you have a regular function that is being passed as a parameter of a suspending type:

val processingFunction = ::processItem
flow.collect(processingFunction) // ERROR: Type mismatch

In Kotlin 1.6, the above code compiles and works, too.

Improved type inference for recursive generic types

From 1.6.0, the Kotlin compiler can infer a type argument based only on the upper bounds of the corresponding type parameter if it is a recursive generic by default. This makes it possible to create various patterns with recursive generic types that are often used in Java to make builder APIs.

// Before 1.5.30
val containerA = PostgreSQLContainer<nothing>(DockerImageName.parse("postgres:13-alpine")).apply {
    withDatabaseName("db")
    withUsername("user")
    withPassword("password")
    withInitScript("sql/schema.sql")
}

// With compiler option in 1.5.30 or by default starting with 1.6.0
val containerB = PostgreSQLContainer(DockerImageName.parse("postgres:13-alpine"))
    .withDatabaseName("db")
    .withUsername("user")
    .withPassword("password")
    .withInitScript("sql/schema.sql")

Builder inference improvements

Kotlin 1.5.30 introduced the -Xunrestricted-builder-inference compiler option, which made type information about a builder call available to get inside builder lambdas. Namely, it introduced the ability of making calls that return an instance of a not yet inferred type, such as get() inside a buildList() lambda.

Starting with 1.6.0, you don’t need to specify -Xunrestricted-builder-inference to make previously prohibited calls. With the -Xenable-builder-inference compiler option, you can now also write your own generic builders without applying the @BuilderInference annotation and automatically enable builder inference if regular type inference cannot resolve type information.

Supporting previous API versions for a longer period

Starting with Kotlin 1.6.0, you can now develop using three previous API versions instead of two (along with the current stable one). Currently, this includes API versions 1.3, 1.4, 1.5, and 1.6.

Kotlin/JVM

Repeatable annotations with runtime retention. Kotlin, like Java 8, has repeatable annotations. With Kotlin 1.6, the feature is compatible with Java, and @kotlin.annotation.Repeatable now accepts any retention and makes the annotation repeatable both in Kotlin and Java. Java repeatable annotations are now also supported from the Kotlin side.

Kotlin/Native

Now you can try the Experimental version of the new Kotlin/Native memory manager. With this feature we are moving closer to providing a consistent developer experience in multiplatform projects. This means that the new memory manager lifts the existing restrictions on object sharing between threads and provides fully leak-free concurrent programming primitives that are safe and don’t require any special management or annotations from the developers.

You can freely update your Xcode and continue working on your Kotlin projects, as Kotlin/Native now supports Xcode 13

Compilation of Windows targets on any host. You can compile Windows targets mingwX64 and mingwX86 on any host that supports Kotlin/Native.

We’ve reworked the LLVM dependency that Kotlin/Native uses under the hood. This brings some benefits along with an updated LLVM version to 11.1.0 and decreased dependency size.

Unified compiler plugin ABI with JVM and JS IR backends. Now, the Kotlin Multiplatform Gradle plugin is able to use the embeddable compiler jar – the one used for JVM and JS IR backends – for Kotlin/Native. You can now use the same compiler plugin artifacts for Native and other supported platforms.

Kotlin/JS

For building on a server without internet connectivity, you can now disable downloading Node.js and Yarn for Kotlin/JS projects and use the instances already installed on the host.

Kover

Since the first release, precise measurement of code coverage has been a challenge. Some great tools like JaCoCo work with Kotlin code, but they are not fully integrated with our Gradle toolchain and multiplatform projects. In this Kotlin release, we have started to fix this issue. Meet Kover, our new Gradle plugin that measures code coverage for Kotlin code built with the Kotlin/JVM compiler. Now it is in the early development stage and is experimental – we would appreciate your feedback on it in GitHub.

Watch the Kover video for more details.

Standard library

Kotlin 1.6.0 completes three stdlib roadmap items by getting rid of !! after readLine(), stabilizing typeOf(), and providing a Stable Duration API. It also promotes the following stdlib functions to Stable:

  • Collection builders
  • Bit rotation operations on integers
  • Regex function for splitting a string into a sequence

We’ve also added the ability to call compareTo in infix notation and invested in providing a consistent experience with replace() functions on JVM and JS.

New functions for standard input

In Kotlin 1.6.0, we got rid of the need to use the not-null assertion operator !! after reading a line from the standard input in order to improve the experience for newcomers and simplify teaching Kotlin.

We provide new functions for reading from the console with the following experience:

  • readln() throws an exception when EOF has been reached. Use this function instead of checking the result of readLine() for null with the !! operator.
  • The new readlnOrNull() is a null-returning alternative. It behaves in the same way as the former readLine() but has a more representative name.

These functions are now available for JVM and Native. The naming convention for these functions is now consistent with the println() counterpart, which is especially important for newcomers.

fun main() {
    println("Input two integer numbers each on a separate line")
    val num1 = readln().toInt()
    val num2 = readln().toInt()
    println("The sum of $num1 and $num2 is ${num1 + num2}")
}

Stable Duration API

Thanks to your feedback, we have stabilized the Duration API and closed the corresponding roadmap item.

In addition to a more readable output of Duration.toString() and new functions for parsing Duration from String that were available for preview in 1.5.30, the Duration API has received the following changes:

  • The days component of the toComponents function now has the Long type instead of Int to avoid cutting off values.
  • The DurationUnit enum is now not a type alias. There are no cases of using it as a type alias for java.util.concurrent.TimeUnit on JVM.
  • In response to community feedback, we’re bringing back extension properties like Int.seconds. To limit their applicability, they are available only in the Companion of the Duration class.
import kotlin.time.Duration.Companion.seconds

fun main() {
//sampleStart
    val duration = 5000.seconds
    println("There are ${duration.inWholeMinutes} minutes in ${duration.inWholeHours} hours")
//sampleEnd
}

Stable typeOf()

Kotlin 1.6.0 brings Stable typeOf() and closes the corresponding roadmap item. Since 1.3.40, typeOf() has been available on the JVM platform as an experimental API, and now you can use it on any Kotlin platform and get a KType representation of any Kotlin type that the compiler can infer. 

inline fun <reified T> renderType(): String {
    val type = typeOf<T>()
    return type.toString()
}

fun main() {
    val fromExplicitType = typeOf<Int>()
    val fromReifiedType = renderType<List<Int>>()
}

Stable collection builders

Kotlin 1.6.0 promotes collection builder functions – buildMap(), buildList(), and buildSet()– to Stable. Collections returned by the builders are now serializable in their read-only state.

Stable bit rotation operations for integers

In Kotlin 1.6.0, the rotateLeft() and rotateRight() functions, which rotate the binary representation of the number left or right by the specified number of bits, became Stable.

fun main() {
//sampleStart
    val number: Short = 0b10001
    println(number.rotateRight(2).toString(radix = 2)) // 100000000000100
    println(number.rotateLeft(2).toString(radix = 2))  // 1000100
//sampleEnd
}

Stable Regex function for splitting a string into a sequence

Kotlin 1.6.0 also stabilizes splitToSequence() – a function for regular expressions that splits a string into a sequence.

fun main(){
//sampleStart
    val colorsText = "green, red , brown&blue, orange, pink&green"
    val regex = "[,\s]+".toRegex()
    val mixedColor = regex.splitToSequence(colorsText)
        .onEach { println(it) }
        .firstOrNull { it.contains('&') }
    println(mixedColor) // "brown&blue"
//sampleEnd
}

compareTo in infix notation

We’ve added the ability to call the Comparable.compareTo function in infix notation to compare two objects for order: 

class WrappedText(val text: String) : Comparable<WrappedText> {
    override fun compareTo(other: WrappedText): Int =
        this.text compareTo other.text
}

Consistent replace() and replaceFirst() on JVM and JS

Before Kotlin 1.6.0, the replace() and replaceFirst() Regex functions behaved differently on JVM and JS when the replacement string contained a group reference. The behavior on Kotlin/JS is now consistent with that on JVM.

​​Compatibility

As with all feature releases, some deprecation cycles of previously announced changes are coming to an end with Kotlin 1.6.0. All of these cases were carefully reviewed by the language committee and are listed in the Compatibility Guide for Kotlin 1.6. You can also explore these changes on YouTrack.

How to install Kotlin 1.6.0

If you’re using IntelliJ IDEA or Android Studio, your IDE will suggest updating Kotlin to 1.6.0 automatically. Alternatively, you can update manually by following these instructions.

You can download the latest versions of these IDEs to get extensive support for Kotlin:

  • IntelliJ IDEA – for developing Kotlin applications for various platforms.
  • Android Studio –  for developing Android and cross-platform mobile applications.

Make sure that you have also updated the kotlinx libraries to the compatible versions and specified Kotlin 1.6.0 in the build scripts of your existing projects.

If you need the command-line compiler, download it from the Github release page.

If you run into any problems:

Stay up to date with the latest Kotlin features! Subscribe to receive Kotlin updates by filling out the form to the right of this post.

What else to read and watch

Top issue reporters from YouTrack 

Ryan Nett (48 issues), Zac Sweers (22 issues), Tianyu Geng (18 issues), zhelenskiy (18 issues), Thodoris Sotiropoulos (15 issues), AndroidDeveloperLB (14 issues), Morgan, Bartholomew (14 issues), Mikhail Naftal (14 issues), Louis CAD (12 issues), Philip Wedemann (12 issues), Victor Turansky (11 issues), Igor Wojda (11 issues), Martin Bonnin (11 issues), Iaroslav Postovalov (11 issues), Cedric (10 issues), (9 issues), Ben Woodworth (8 issues), Tianyi Guan (8 issues), Chris Povirk (8 issues), Alon Albert (8 issues).

External contributors

We’d like to thank all of our contributors whose pull requests were included in this release: Pyos, Tianyu Geng, Jinseong Jeon, Steven Schäfer, Mark Punzalan, Hung Nguyen, Mads Ager, Ting-Yuan Huang, Matthew Gharrity, Ivan Gavrilovic, Xin Wang, ov7a, Jiaxiang Chen, Yigit Boyar, Bingran, bracadabra, Steffi Stumpos.

Continue ReadingKotlin 1.6.0 Released

Kotlin 1.5.30 Is Now Available!

Since Kotlin 1.5.30 is the last incremental release before Kotlin 1.6.0, it includes many experimental language and standard library features that we are planning to release in Kotlin 1.6.0. Give them a try and share your feedback with us, you can really influence the final result! These experimental features include sealed when statements, changes to opt-in requirements, instantiation of annotation classes, improvements to the Duration and Regex stdlib APIs, and more.

With Kotlin 1.5.30, you can also enjoy native support for Apple silicon, the promotion of the Kotlin/JS IR backend to Beta, the ability to use custom cinterop libraries in the shared native code of multiplatform applications, support for Java toolchains provided by the Kotlin Gradle plugin, and much more.

Update to Kotlin 1.5.30

This blog post provides an overview of the updates in this release:

  • Language improvements, including sealed when statements, support for suspend functions as supertypes, and changes to opt-in requirements.
  • Multiplatform improvements, including the ability to use custom cinterop libraries in shared native code and support for XCFrameworks as an output format.
  • Kotlin/JVM improvements, including instantiation of annotation classes and improved configuration of nullability annotation support.
  • Kotlin/Native improvements, including native support for Apple silicon and an improved Kotlin DSL for the CocoaPods Gradle plugin.
  • Kotlin/JS IR improvements, including the promotion of the JS IR backend to Beta and a better debugging experience for the new backend.
  • Gradle improvements, including support for Java toolchains and easier ways to explicitly set the Kotlin daemon’s JVM arguments.
  • Standard library improvements for the Duration and Regex APIs.

Automatically update to Kotlin 1.5.30

If you use IntelliJ IDEA or Android Studio, you have the option to automatically update to the new Kotlin release as soon as it becomes available.

Learn more about installing Kotlin 1.5.30.

Stay up to date with information about the latest Kotlin features! Subscribe to receive Kotlin updates by filling out the form to the right of this post.

Language

The Kotlin roadmap includes adding support for sealed when statements, releasing opt-in annotations, improving type inference, and stabilizing builder inference. 

Kotlin 1.5.30 takes a step down this road by providing a preview of these features, whose release is planned for 1.6.0.

Sealed when statements

Sealed when is a long awaited feature with more than 280 votes in YouTrack. If you enable this feature in 1.5.30, the Kotlin compiler will warn if one of your when statements is not exhaustive. This will make your code safer without you having to introduce your own functions.

Give this feature a try and provide your feedback in this YouTrack ticket

Support for suspend functions as supertypes

Kotlin 1.5.30 provides a preview of an ability to use suspend functional types as super interfaces, although it has some limitations. It’s one of the missing pieces in the Kotlin coroutines design.

class MyClass: suspend () -> Unit {
    override suspend fun invoke() { TODO() }
}

Enable this feature, give it a try, and provide your feedback in this YouTrack ticket.

Changes to opt-in requirements

As a further step toward the release of opt-in annotations, Kotlin 1.5.30:

  • Presents new rules for using and declaring opt-in requirement annotations on different targets. 
  • Requires opt-in even for implicit usages of an experimental API. For example, if the function’s return type is marked as an experimental API element, a usage of the function requires you to opt-in even if the declaration is not marked as requiring an opt-in explicitly.
// Library code

@RequiresOptIn(message = "This API is experimental.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS)
annotation class MyDateTime // Opt-in requirement annotation

@MyDateTime
class DateProvider // A class requiring opt-in

// Client code

// Warning: experimental API usage
fun createDateSource(): DateProvider { /* ... */ }

fun getDate(): Date {
    val dateSource = createDateSource() // Also warning: experimental API usage
    // ... 
}

Try out the changes and share your feedback in this YouTrack ticket

Learn more about opt-in requirements

Improvements to type inference on recursive generic types 

With type inference on recursive generic types enabled, the Kotlin 1.5.30 compiler can infer a type argument based only on the upper bounds of the corresponding type parameter if it is a recursive generic. This makes it possible to create various patterns with recursive generic types that are often used in Java to make builder APIs.

// Kotlin 1.5.20
val containerA = PostgreSQLContainer<Nothing>(DockerImageName.parse("postgres:13-alpine")).apply {
    withDatabaseName("db")
    withUsername("user")
    withPassword("password")
    withInitScript("sql/schema.sql")
}

// Kotlin 1.5.30
val containerB = PostgreSQLContainer(DockerImageName.parse("postgres:13-alpine"))
    .withDatabaseName("db")
    .withUsername("user")
    .withPassword("password")
    .withInitScript("sql/schema.sql")

Eliminating builder inference restrictions 

With eliminating builder inference restrictions enabled, Kotlin 1.5.30 removes a builder inference restriction. Not only can you specify the type information that builder inference can infer, but you can also use the get function on it. For example, you can call get() inside a lambda argument of buildList() without explicitly specified type arguments.

Kotlin Multiplatform

Kotlin 1.5.30 includes the following improvements for Kotlin Multiplatform:

  • Ability to use custom cinterop libraries in shared native code, which extends the ability to share platform-dependent libraries shipped with Kotlin/Native. 
  • Support for XCFrameworks as an output format for all Kotlin Multiplatform projects. XCFrameworks help gather logic for all the target platforms and architectures in a single bundle and don’t require removing unnecessary architectures before publishing the application to AppStore.
  • New default publishing setup for Android artifacts. This setup will be compatible with any build type (like debug or release)  by default. Before 1.5.30, the metadata generated by the maven-publish Gradle plugin when publishing a multiplatform library for Android included the build type attribute for every published Android variant. This made it compatible only with the same build type used by the library consumer. 

Kotlin/JVM

With Kotlin 1.5.30, Kotlin/JVM gets the following updates:

annotation class InfoMarker(val info: String)

fun processInfo(marker: InfoMarker) = ...

fun main(args: Array<String>) {
    if (args.size != 0)
        processInfo(getAnnotationReflective(args))
    else
        processInfo(InfoMarker("default"))
}

Kotlin/Native

Kotlin 1.5.30 provides the following improvements for Kotlin/Native:

Kotlin/JS

Kotlin 1.5.30 provides the following improvements for Kotlin/JS:

Gradle

Kotlin 1.5.30 introduces the following features to improve the Kotlin Gradle plugin user experience:

  • Support for Java toolchains. Gradle 6.7 introduced support for Java toolchains, which make it easy to select a JDK for project compilation. Just declare the version you need in the build script and Gradle does the rest, finding it on your host machine or even downloading and installing it if it’s not there yet. The Kotlin Gradle plugin supports Java toolchains for Kotlin/JVM compilation tasks. For Gradle versions 6.1-6.6, set a JDK home with the UsesKotlinJavaToolchain interface.
  • Easier ways to explicitly specify Kotlin daemon JVM arguments. If nothing is specified for the Kotlin daemon, it inherits arguments from the Gradle daemon. You can now also specify arguments for a specific task, as well as for the Kotlin extension, as a single line in build.gradle.kts or gradle.properties.

build.gradle.kts

kotlin {
    kotlinDaemonJvmArgs = listOf("-Xmx486m", "-Xms256m", "-XX:+UseParallelGC")
}

gradle.properties

kotlin.daemon.jvmargs = -Xmx486m -Xms256m -XX:+UseParallelGC

Standard library

Kotlin 1.5.30 brings improvements to the standard library’s Duration and Regex APIs:

Duration API improvements

As indicated in our libraries roadmap, we’re going to stabilize the Duration API in Kotlin 1.6.0, which means this is the last chance to give it a try and share your feedback with us on anything you’d like changed. We would appreciate your feedback in this KEEP.

Kotlin 1.5.30 provides a preview of API improvements. The output of Duration.toString() is now more readable. For example, Duration.minutes(920).toString() produces 15h 20m instead of the previous 920m.

A negative duration is now prefixed with a minus sign (-), and it is surrounded by parentheses if it consists of multiple components: -12m and -(1h 30m).

This release also provides a preview of new functions for parsing Duration from String:

  • parse() parses Duration objects from strings formatted as Duration’s toString() or from strings representing ISO 8601 durations (such as toIsoString() outputs).
  • parseIsoString() parses Duration objects from strings representing ISO 8601 durations.
  • *OrNull() counterparts for both functions.
import kotlin.time.Duration
import kotlin.time.ExperimentalTime

@ExperimentalTime
fun main() {
//sampleStart
    val isoFormatString = "PT1H30M"
    val defaultFormatString = "1h 30m"
    println(Duration.parse(isoFormatString)) // "1h 30m"
    println(Duration.parse(defaultFormatString)) // "1h 30m"
//sampleEnd
}

Regex API improvements

Kotlin 1.5.30 provides new experimental functions for regular expressions:

  • matchesAt() checks whether a regex has a match in the specified position of a String.
  • matchAt() returns the match if one is found.
fun main(){
//sampleStart
    val releaseText = "Kotlin 1.5.30 is released!"
    val versionRegex = "\d[.]\d[.]\d+".toRegex()
    println(versionRegex.matchAt(releaseText, 0)) // "null"
    println(versionRegex.matchAt(releaseText, 7)?.value) // "1.5.30"
//sampleEnd
}
  • splitToSequence() is a lazy counterpart of split(). It splits the string around matches of the given regex, but returns the result as a Sequence. A similar function has also been added to CharSequence.
fun main(){
//sampleStart
    val colorsText = "green, red , brown&blue, orange, pink&green"
    val regex = "[,\s]+".toRegex()
    val mixedColor = regex.splitToSequence(colorsText)
        .onEach { println(it) }
        .firstOrNull { it.contains('&') }
    println(mixedColor) // "brown&blue"
//sampleEnd
}

How to install Kotlin 1.5.30

If you already use IntelliJ IDEA or Android Studio, your IDE will suggest updating Kotlin to 1.5.30 automatically. You can also update manually by following these instructions

You can download the latest versions of these IDEs to get extensive support for Kotlin:

  • IntelliJ IDEA – for developing Kotlin applications for various platforms.
  • Android Studio –  for developing Android and cross-platform mobile applications.

Make sure that you have also updated the kotlinx libraries to compatible versions and specified version 1.5.30 of Kotlin in the build scripts of your existing projects.

If you need the command-line compiler, download it from the Github release page.

If you run into any problems

Stay up to date with information about the latest Kotlin features! Subscribe to receive Kotlin updates by filling out the form to the right of this post.

Read and watch more

External contributors 👏👏👏

We’d like to thank all of our external contributors whose pull requests were included in this release:

Jinseong Jeon, pyos, Tianyu Geng, Mark Punzalan, Mads Ager, Ivan Gavrilovic, Steven Schäfer, Vladimir Ivanov, Hung Nguyen, Matthew Gharrity, Jiaxiang Chen, Ivan Kochurkin, Iaroslav Postovalov, Toshiaki Kameyama, Udi Cohen, Xin Wang, bracadabra

Continue ReadingKotlin 1.5.30 Is Now Available!

Kotlin 1.5.30-RC With Java Toolchains in Gradle, JS IR Backend in Beta, Stdlib Improvements, and More

The 1.5.30 release is approaching, and now we’re presenting the release candidate with the updated opt-in requirements, Kotlin/JS IR backend in Beta, support for Java toolchains in the Gradle plugin, improvements to the Regex and Duration API in the standard library, and more. Try it and report any issues you face to help us prepare the final release.

We’ve unveiled the first set of Kotlin 1.5.30 features with the 1.5.30-M1 preview. In this post, we’ll briefly describe some more of the new features that you can try with Kotlin 1.5.30-RC:

Try new features

Opt-in requirements

Kotlin’s opt-in requirement mechanism has been available in the Experimental state for quite some time, and releasing it as Stable is on our roadmap. In 1.5.30, we’re changing the behavior of the opt-in requirements to make it more consistent and less error-prone:

  • An opt-in is now required for implicit usages of the marked API, for example, if it’s used as a function’s return type.
  • Opt-in annotations are now prohibited on more declarations, including local variables, value parameters, backing fields, and getters.
  • Overriding methods can only have opt-in annotations that are present on their basic declarations.
  • Opt-in annotations can’t have TYPE and TYPE_PARAMETER targets.

Instantiation of annotation classes

The ability to create instances of annotation classes by calling their constructors is another improvement on the Kotlin roadmap. In 1.5.30-RC, we’re adding the opt-in support for this ability to the JVM.

To allow creation of annotation instances with constructors, switch to the language version 1.6 by adding the -language-version 1.6 compiler option. You can find more details about this feature in this KEEP.

JS IR backend in Beta

The IR-based backend for the Kotlin/JS compiler has been in Alpha since Kotlin 1.4.0. We never stopped working on it, and in 1.5.30 it will become Beta. This means that we don’t expect breaking changes anymore and its future development will be mainly focused on stabilization. 

How to migrate

Gradle: Java toolchain support and JVM options for Kotlin daemon in the build script

Gradle 6.7 introduced the support for Java toolchains – an easy way to select a JDK for the project compilation. Just declare the version you need in the build script, and Gradle does the rest, finding it on your host or even downloading and installing it if it’s not there yet.

Kotlin 1.5.30-RC enables Java toolchain support for Kotlin compilation tasks:

kotlin {
    toolchain {
        (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(<MAJOR_JDK_VERSION>)
    }
}

Other Gradle-related improvements include new ways to provide JVM options for the Kotlin Gradle daemon. Now you can specify them in a separate line in gradle.properties:

kotlin.daemon.jvmargs = "-Xmx486m -Xms256m -XX:+UseG1GC"

or in build.gradle.kts:

kotlin {
   kotlinDaemonJvmArgs = listOf("-Xmx486m", "-Xms256m", "-XX:+UseG1GC")
}

Regex and Duration API improvements

Kotlin’s Regex API is receiving new experimental functions:

  • matchesAt() checks if a regex has a match in the specified position of a String. It’s accompanied by matchAt() that returns the match itself if it is found.
val releaseText = "Kotlin 1.5.30 is coming!"
// regular expression: one digit, dot, one digit, dot, one or more digits
val versionRegex = "\d[.]\d[.]\d+".toRegex()
println(versionRegex.matchesAt(releaseText, 7)) // "true"
println(versionRegex.matchAt(releaseText, 7)?.value) // "1.5.30"
  • splitToSequence() – a lazy counterpart of split() –  splits the string around matches of the given regex, but returns the result as a Sequence. A similar function is also added to CharSequence.
val phoneNumber = "+7 (123) 456-78-90"
val regex = "[ ()-]+".toRegex()
val parts = phoneNumber.splitToSequence(regex)
// or
// val parts = regex.splitToSequence(phoneNumber)

// any processing operation on parts are executed lazily

The experimental Duration API has also been updated in 1.5.30-RC:

  • The output of Duration.toString() has become more readable. For example, Duration.minutes(2415).toString() produces 1d 16h 15m instead of 40.3h.
  • Duration also receives new functions for parsing from strings:
    • parse() parses Duration objects from strings formatted as Duration’s toString() or strings representing ISO 8601 durations (such as toIsoString() outputs).
    • parseIsoString() parses Duration objects from strings representing ISO 8601 durations. Both parsing functions come with *OrNull() counterparts.
import kotlin.time.Duration
import kotlin.time.ExperimentalTime

@ExperimentalTime
fun main(){
    val isoFormatString = "PT1H30M"
    val defaultFormatString = "1d 1h 15m"
    println(Duration.parseIsoString(isoFormatString)) // "1h 30m"
    println(Duration.parse(defaultFormatString)) // "1d 1h 15m"
    //println(Duration.parseIsoString(defaultFormatString)) // throws exception
    println(Duration.parseIsoStringOrNull(defaultFormatString)) // "null"
}

Try the new features and report issues

All Kotlin 1.5.30 features (including those presented in the 1.5.30-M1 preview) are available in the release candidate 1.5.30-RC. You can easily install it in your IDE – IntelliJ IDEA or Android Studio – in any of these ways: 

  • If you use the Early Access Preview update channel, the IDE will suggest updating to 1.5.30-RC automatically once it is out.
  • If you use the Stable update channel, you can change the channel to Early Access Preview at any time by selecting Tools | Kotlin | Configure Kotlin Plugin Updates in your IDE, then you’ll be able to install the latest preview release. Check out these instructions for details.

You can always download the latest versions of these IDEs to get extensive support for Kotlin:

  • IntelliJ IDEA for developing Kotlin applications for a variety of platforms.
  • Android Studio for developing Android and cross-platform mobile applications.

Note: the latest version of IntelliJ IDEA – 2021.2 – doesn’t support Kotlin 1.5.30 previews. If you have already upgraded to this version, you can easily install the previous version (2021.1) using the JetBrains Toolbox App and try Kotlin 1.5.30-RC in that version.

Once you’ve installed 1.5.30-RC, change the Kotlin version to 1.5.30-RC in your build scripts. 

If you run into any problems:

Read more

Continue ReadingKotlin 1.5.30-RC With Java Toolchains in Gradle, JS IR Backend in Beta, Stdlib Improvements, and More

kotlinx.serialization 1.2 のリリース: JSON 高速処理、値クラスのサポート、ドキュメントの見直しなど

先日、kotlinx.serialization 1.2 がリリースされました! 当社のマルチプラットフォーム向けシリアル化ライブラリの最新バージョンにはいくつかの改善点が盛り込まれています。以下、その概要を紹介します。

バージョン 1.2 には、JSON フィールドの代替名に対するサポートが新しく盛り込まれているほか、それにより、Kotlin クラスから自動的に Protobuf スキーマを生成する新しい実験的なアプローチも提供されています。この機能については、ぜひご意見をお聞かせください!

それでは、今回の新バージョンに関する変更点や追加機能を一緒に見ていきましょう! 既に十分理解されているという方は、下のアップグレード手順にジャンプしていただいて構いません!

kotlinx.serialization 1.2 を始める!

Kotlin YouTube チャンネルに登録!!

これまでで最速となる JSON のエンコード・デコード

Kotlin クラスを JSON の文字列にエンコードする機能と JSON の文字列を Kotlin クラスに変換する機能は、kotlinx.serialization の機能の中で最も一般的に使用されるものであるため、当社は常にパフォーマンスの改善に取り組んでいます。

kotlinx.serialization を使った JSON の解析: 最高で 55% もスピードアップ

バージョン 1.2 では、kotlinx.serialization の内部構造が全面的に見直され、このコア機能のパフォーマンスが大幅に改善されています。 JSON デコーダー (テキストを Kotlin オブジェクトに変換) を書き直し、JSON エンコーダー (Kotlin オブジェクトをテキストに変換) に対する大幅な最適化も実施しました。

kotlinx.serialization を使った JSON のエンコード: 最高で 339% もスピードアップ

最新のライブラリにアップグレードするだけで、典型的なエンコードとデコードの処理速度が最高で 2 倍もアップすることが期待できます。 (見てお分かりの通り、内部ベンチマークの中には、こうした新しい最適化が大きなメリットとなり、この数字を超えるものもあります!)

こうした変更が加えられたことで、kotlinx.serialization は、そのままの状態で JSON の他のライブラリと同等のパフォーマンスを実現し、いくつかの点ではより高いレベルに達しています。 今回の見直しでは、とてもシンプルなスニペットにまでメリットがあります。

@Serializable
data class User(val name: String, val yearOfBirth: Int)

fun main() {
// Faster encoding...
val data = User("Louis", 1901)
val string = Json.encodeToString(data)
println(string) // {"name":"Louis","yearOfBirth":1901}

// ...and faster decoding!
val obj = Json.decodeFromString(string)
println(obj) // User(name=Louis, yearOfBirth=1901)
}

当社のライブラリの最新バージョンを基準にご自分のアプリケーションを評価すれば、こうした改善内容の効果を最も強く実感していただけると思います。 パフォーマンス数値の大まかな傾向は、エンコードデコードに関する当社の内部ベンチマークをご覧ください。kotlinx.serialization の最新バージョンと前のリリースを比較した内容となっています。

値クラスと符号なしの数値型に対する JSON シリアル化 (逆シリアル化) が stable に

Kotlin 1.5.0 では、値クラス符号なし整数型 という 2 つの便利な機能が追加されています。これらに対し、kotlinx.serialization 1.2 では、JSON のエンコードおよびデコードに対するファーストクラスのサポートが導入されました。 では、詳しく見てみましょう。

値クラスのサポート

値クラス (旧名 inline クラス) は、Kotlin の別の型 (number など) を実行時のオーバーヘッドを増やさずに型安全な手段を使ってラップするための方法です。 これにより、プログラムをより詳細に表現できるほか、安全性を高めることもできるため、パフォーマンスが低下することもありません。

kotlinx.serialization に備えられている JSON のシリアル化機能は値クラスに対しても使えるようになりました。 Kotlin の他のクラスと同様に、value class@Serializable のアノテーションを付けるだけで OK です。

@Serializable
value class Color(val rgb: Int)

値クラスは、その基底型として直接保存 (およびシリアル化) されます。 これは、value class 型のフィールドをシリアル化可能なデータクラスに追加し、その出力を検査すれば確認できます。

@Serializable
data class NamedColor(val color: Color, val name: String)
fun main() {
println(Json.encodeToString(NamedColor(Color(0), "black")))
}

// {"color": 0, "name": "black"}

上の例の NamedColor では、値クラス Color基底のプリミティブ型 (Int) として扱われています。 つまり、こうした型を正確にシリアル化した表現のメリットを得ながら、Kotlin コード内で最大の型安全を活用でき、不要なボックス化やネストは行う必要がありません。

値クラス用のカスタムシリアライザのデザインは、現在も改良中ですので、現時点でも実験的な使用となってます。 このトピックに関する詳細は、GitHub に記載のこちらの docs をご覧ください。

符号なし整数のサポート

符号なし整数は、Kotlin の標準ライブラリに新たに加わった種類の整数で、負以外の数値の型を使用したり、演算を行ったりすることができます。 Kotlin 1.5.0 のリリースにより、以下の符号なし数値型を使用できるようになりました。

  • UByte、0~255 の値
  • UShort、0~65535 の値
  • UInt、0~2^32 – 1 の値
  • ULong、0~2^64 – 1 の値

kotlinx.serialization の JSON エンコーダーとデコーダーは、初期設定の状態でこれらの型をサポートしています。 他の数値型と同様に、符号なし整数型も切り捨てやラッピング、符号付きの型への変換などはされずに、通常の数値表現 (.toString を呼び出したときと同じ表現) でシリアル化されます。

@Serializable
class Counter(val counted: UByte, val description: String)

@Serializable
class BigCounter(val counted: ULong)

val counted = 239.toUByte()
println(Json.encodeToString(Counter(counted, "tries")))
// {"counted":239,"description":"tries"}

println(Json.encodeToString(BigCounter(ULong.MAX_VALUE)))
// {"counted":18446744073709551615}

値クラスと符号なし整数の使用は、現在 JSON でサポートされています。 今後のリリースでは、CBOR と Protobuf の直接的な統合も提供しますので、ご期待ください!

kotlinx.serialization やプログラミング言語 Kotlin の今後のリリースに関する最新情報を把握しておきたい方は、本ブログ記事の横にあるフォームより Kotlin 製品の最新情報に関するニュースレターに登録してください。

kotlinx.serialization における値クラスと符号なし型の使用に関する詳細は、documentation on GitHub をご覧ください。

JSON フィールドに使う代替名のサポート

後方互換性を維持するためなどの理由から、意味は同じでも、名前が異なる JSON フィールドをパースしないといけない場合があります。 新しい @JsonNames アノテーションを使えば、JSON フィールドに代替名を付けられるようになりました。この代替名はデコーディングのプロセスを通して使用されます。

これを説明するために、例を 1 つ見てみましょう。 バージョンにより、サーバーは以下の 2 つのレスポンスのどちらかを返すと仮定しましょう。

{"name":"kotlinx.serialization"}
/* ...or: */
{"title":"kotlinx.serialization"}

nametitle は、ともに同じ意味を持っているため、これらを私たちの Kotlin クラス内にある同じフィールドにマッピングしたいとします。 新しい @JsonNames アノテーションを使用すれば、titlename キーの代替キーとして指定することができます。

@Serializable
data class Project(@JsonNames("title") val name: String)

これは、エンコーディングとデコーディングの両方でフィールドの名前変更を許可する一方で、代替の指定は許可しないという @SerialName アノテーションとは異なることに注意してください。

この機能により、同じ値を意味するが違う名前を持つフィールドを返すサービスの操作やスキーマの移行、アプリケーションのスムーズなアップグレードが簡単に行えるようになることを期待しています!

新しくなった API ドキュメント

kotlinx.serialization をできるだけ安心して、楽しく学んでいただけるよう、当社は数多くの参照資料を提供することに努めています。 その 1 つが Kotlin Serialization Guide on GitHub です。ライブラリが提供する機能の手引きとなっており、大切なポイントをすべて盛り込んだ例がいくつも含まれているため、各機能を直感的に理解できるなっています。

他にも、全面的に改訂した kotlinx.serialization API documentation があります。 Kotlin のドキュメンテーションエンジン Dokka の最新バージョンに基づき、新しい API ドキュメントには、新しいレスポンシブかつモダンなデザインや理解しやすいシンボルが採用されています。

新しい API ドキュメントの例、表示されているのは JsonElement ドキュメント

kotlinx.serialization の新しくなった API ドキュメントを詳しくご覧ください!

Protobuf: Kotlin クラスからのスキーマ生成の実験的サポート

Protocol Buffers (Protobuf) は、Google が開発したバイナリシリアル化の形式であり、構造化されたデータに使用されます。 バイナリ形式であるため、JSON や XML よりも空間効率が優れていると同時に、アプリケーション間でのコミュニケーションに使用できる言語に依存しない構造を提供します。

kotlinx.serialization では、実験的安定性(experimental)としてマルチプラットフォーム対応の Protobuf を使ったシリアル化 (proto2 セマンティクスを使用) を行えます。 他の形式と同様に、クラスは @Serializable として注釈し、ビルトインメソッド encode / decode を使用します。

@Serializable
data class Project(val name: String, val language: String)

fun main() {
val data = Project("kotlinx.serialization", "Kotlin")
val bytes = ProtoBuf.encodeToByteArray(data)
println(bytes.toAsciiHexString())
val obj = ProtoBuf.decodeFromByteArray(bytes)
println(obj)
}

Kotlin クラスをいわゆる信頼できる情報源(source of truth)とし、また便利なカスタマイゼーションも使用することにより、 kotlinx.serialization は、データのバイナリスキーマを推論することが可能です。これによりProtobuf コミュニケーションを複数の Kotlin アプリケーション間で簡潔で便利に行うことができるようになります。

kotlinx.serialization 1.2 には、Protocol Buffers の実験的なスキーマジェネレーターも搭載されました。 Kotlin のデータクラスから .proto ファイルを生成することができます。また、それを使って Python や C++, TypeScript など、他の言語でコミュニケーションスキーマを表現することができます。

新しいスキーマジェネレーターの使用を開始する手順については、ドキュメントの該当する手順をご覧ください。

.proto ファイルが生成されたら、リポジトリに保管し、他の言語で表現された Kotlin クラスを生成することに使用できます。 これにより、Kotlin のソースコード内で直接スキーマを管理できるという利便性を維持しながら、複数言語のアプリケーションでも kotlinx.serialization が提供する Protobuf との統合を簡単に活用できるようになることを期待しています。

これは Protobuf スキーマジェネレーターの最初のイテレーションということもあり、皆さまからのフィードバックを特に重要視しています。 是非ともお試しください。皆さまのユースケース、モデルや .proto ファイルの管理方法、直面した問題、あればいいなと思われる機能などを GitHub の課題トラッカーより知らせください。

スキーマジェネレーターを使用する際は、いくつか制限がありますので覚えておきましょう。 大まかな原則としては、kotlinx.serialization に搭載されている protobuf の実装を使って Kotlin クラスをシリアル化できる場合は、スキーマジェネレーターがそれをサポートするようになっています。 これは、同じ制限が適用されるということでもあります。 以下、注意点をいくつか紹介します。

  • Kotlin のクラス名とプロパティ名は、protobuf の仕様に準拠する必要があり、不正な文字を含まない。
  • Kotlin の null 許容性はスキーマに反映されない (proto2 はそれ専用のセマンティクスを持たないため)。 Protocol Buffer が提供するオプションのフィールドは、Kotlin のプロパティがデフォルト値を定義するかどうかに基づいて使用される。
  • Kotlin のデフォルト値はスキーマに含まれない。 (つまり、別の言語での実装においてもデフォルト値の一貫性を自ら保証する必要があります。)

kotlinx.serialization 1.2 をご使用ください!

本リリースの概要は以上です! JSON の高速化されたエンコーディング・デコーディング機能 や Kotlin 1.5 で新たに追加された型システムのサポート、Protobuf のスキーマ生成などをさっそく活用したいという方は、今すぐアップグレードしてください!

kotlinx.serialization を既に使用されている方は、バージョン 1.2 にすばやくアップグレードしていただけます (kotlinx.serialization をまだお試しでない方は、是非このタイミングで始めてください!) まずは、build.gradle.kts ファイルの plugins ブロックを更新します。

plugins {
kotlin("jvm") version "1.5.0" // or kotlin("multiplatform") or any other kotlin plugin
kotlin("plugin.serialization") version "1.5.0"
}

そして、ランタイムライブラリで dependencies ブロックを更新し、アプリケーションで使用する形式なども一緒に更新します。

dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.1")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.2.1")
// . . .
}

動画とその他の情報

問題に直面した場合

Kotlin YouTube チャンネルにご登録ください! 楽しく (デ) シリアル化しましょう!

Continue Readingkotlinx.serialization 1.2 のリリース: JSON 高速処理、値クラスのサポート、ドキュメントの見直しなど

The Kotlin YouTube Channel

The Kotlin community has always been the greatest source of inspiration for our team. We aspire to make the life of every Kotlin developer better, and we do our best to listen to all your feedback. With the increasing demand for more Kotlin-related video content, we would like to draw your attention to the Kotlin YouTube channel. It will help you connect with other Kotlin enthusiasts, stay up to date with what we are doing in the Kotlin team, and learn new skills from the comfort of your couch.

The Kotlin YouTube channel was launched on January 18, 2021, and has since grown to have more than 9 thousand subscribers, who can expect a new video every week. Over these 2 and a half months, we have introduced a multitude of formats, including pre-recorded videos, live webinars, and a bi-weeikly video podcast.

Subscribe to the Kotlin YouTube channel!

Here is a short summary of all of the series and formats that are currently available:

Spring Time in Kotlin

In this series you will learn how Kotlin and Spring work hand-in-hand to make you more productive while building server-side applications. Together with Anton Arhipov you will build a simple service with a database and extend it to try different Spring APIs. All the episodes are accompanied by code samples, so it will be easy for you to follow along and start using Kotlin to build Spring applications.

Webinars with experts

During our webinars, experts from different companies explain how to use Kotlin for a variety of purposes and answer questions during Q&A sessions. Speakers from JetBrains, VMware, Confluent, and Oracle have covered reactive programming, asynchronous applications with the Ktor framework, building microservices with Helidon, and other aspects of using Kotlin for server-side development. There are also special tracks on competitive programming and Kotlin for education, and more webinars are still to come! Subscribe to take part in the webinars and ask your questions during the live Q&A sessions! Recordings of these events will be also available after on the channel.

Kotlin Standard Library Safari

Learn about the features you get out of the box with Kotlin! If you know how to wield it, the Kotlin standard library is a powerful tool that can help you solve problems more effectively and be more expressive in your code. Together with Sebastian Aigner, we go through the useful functionality the standard library in Kotlin has to offer. In the process, we together unearth some hidden gems that could come in handy the next time you write Kotlin code.

Talking Kotlin

Since 2017, the Talking Kotlin Podcast has been the place to hear from people of different backgrounds and specializations about how they use Kotlin. Following its move to YouTube, Sebastian Aigner has joined Hadi Hariri as a co-host and we have already had conversations about the present and the future of Kotlin with its new project lead, Roman Elizarov, and about Kotlin Multiplatform with John O’Reilly. In each episode we are joined by interesting guests who offer insights into their experiences of using Kotlin in a variety of exciting fields.

Kotlin Multiplatform Multiverse

In this series of videos, Kate Petrova will show you how to use Kotlin Multiplatform Mobile for developing apps for iOS and Android from a single codebase. You will start by creating a simple application and proceed to look at a typical KMM-project structure. After learning the basics of KMM, you will see how to use it in real projects and understand how to make the process of developing cross-platform mobile apps with Kotlin Multiplatform efficient and enjoyable.

Plans for the future

We’re not stopping there. We’re exploring additional formats that will allow us to provide even more Kotlin content for you to enjoy. We have plans to bring more people from the team to the channel and organize special video events dedicated to certain milestones in the language. For example, we plan to do something special for the upcoming Kotlin 1.5 release.

Subscribe to our YouTube channel to never miss a thing!

As we continue to develop the official YouTube channel for Kotlin, we would like to pause for a moment to say thank you to everyone who inspired us to make all of this happen. We love reading your comments under the videos, and we continuously strive to make the channel better and provide content that you, our community, will find helpful. Please leave your ideas for a new series here, or under any of our videos, and we’ll do our best to bring them to the channel.

Continue ReadingThe Kotlin YouTube Channel

New Release Cadence for Kotlin and the IntelliJ Kotlin Plugin

TL;DR

  1. From now on, we will release Kotlin 1.X every six months. These releases will be date-driven, not feature-driven.
  2. The Kotlin IDE plugin will be released simultaneously with Kotlin, and on top of that — every time IntelliJ IDEA is released. Major IDE features will arrive in releases synchronized with IntelliJ IDEA.

Why the new cadence?

Since Kotlin 1.0 came out in 2016, we’ve built our release schedule around new key features in the language. This meant that until big language features were ready we would not release anything at all. As a consequence, we delivered changes and improvements once a year or sometimes even less frequently. The language has evolved more slowly than we would like, and release dates have been somewhat unpredictable for the users.

The main goal of the new date-driven release cadence is to accelerate the delivery of important language updates.

What are the changes in the new cadence?

There are three types of Kotlin releases: feature, incremental, and bug fix releases. However, changes will, for the most part, only affect feature releases. Below is a diagram of the new Kotlin release cadence.

Feature releases (e.g. 1.4, 1.5) will ship updates to the language twice a year– in spring and in autumn – starting from Kotlin 1.5, which is due in spring 2021. Feature releases will become smaller in terms of the changes they bring, and their release dates will be more predictable.

Incremental releases (e.g. 1.3.70, 1.4.20) will ship in between major releases. They will not include language changes, only compiler improvements (e.g. speedups) and tooling changes.

Bug fix releases (e.g. 1.3.71, 1.3.72) will possibly, but not necessarily, follow incremental releases. They mainly contain hotfixes.

Extra notes on the Kotlin IDE plugin

Nowadays, major changes in the Kotlin IDE plugin depend on the IntelliJ Platform more than on the Kotlin compiler. So, from now on, new versions of the Kotlin plugin will ship with every release of the IntelliJ Platform as well as with new versions of Kotlin.

At all times, the IDE support for the latest version of the language will be available for the two latest versions of IntelliJ IDEA and the latest version of Android Studio.

We are in the process of moving the Kotlin IDE plugin to the IntelliJ IDEA codebase to minimize the time it takes us to pick up platform changes, and also make sure that the IntelliJ team gets the latest Kotlin IDE fixes very quickly and dogfoods them efficiently. Also, it will be easier for us to keep the IDE support for Kotlin on par with Java. This is why we synchronize our release cycles.

Summary

Kotlin is evolving quickly and we’re keen to remove any obstacles preventing the team and the community from achieving their goals. Today we’ve introduced two major process improvements, and we believe they will speed up the language progress even more.

If you are interested in the Kotlin team’s plans and the projects we’re currently working on, you can find more information in the recently published Kotlin public roadmap.

Continue ReadingNew Release Cadence for Kotlin and the IntelliJ Kotlin Plugin

Kotlin 1.4 Released with a Focus on Quality and Performance

You can read this blog post in other languages:
日本語, Français, 한국어, Español, Português, Русский, 简体中文

Today we’re releasing Kotlin 1.4.0! Over the past years, we’ve been working hard on making Kotlin a programming language that is fun, enjoyable, and productive to work with. To continue our pursuit of this goal with this version of Kotlin, we put a lot of energy and effort into improving the performance and quality of Kotlin and its tooling. We are also excited to announce support for several new language features, including the long-awaited SAM conversions for Kotlin interfaces.

file

To help you get the most out of the changes and improvements introduced in Kotlin 1.4, we’re inviting all of you to the Kotlin 1.4 Online Event, where you will be able to enjoy four days of Kotlin talks, Q&As with the Kotlin team, and more – completely free.

Community and ecosystem

More than 5.8 million people have edited Kotlin code in the last 12 months, and the numbers are constantly growing:

file

We’re delighted to see how popular Kotlin is becoming! The numbers of active users – we’ll explain this metric in more detail in a future blog post – have been especially encouraging. Here, we are seeing a 1.5-fold increase over the previous year’s figures.

According to the StackOverflow Developer Survey 2020, Kotlin has climbed to 13th place among the most popular programming languages for professional developers, and we’re happy to see that Kotlin is one of the top 5 most loved languages.

Many companies have picked Kotlin as their language of choice, and are successfully using it on all platforms. We’re happy to see this tendency, and we’re tremendously grateful that so many of these companies have made case studies available for the community to read and learn from. Here are just a few amazing examples of software recently developed in Kotlin:

Our Kotlin communities are also growing rapidly. Over 30,000 Kotlin developers are now exchanging knowledge and supporting each other on Slack and Reddit, and more than 90,000 people follow our official Twitter account for tips, tricks, and announcements. With over 200 user groups worldwide, the Kotlin community is thriving and growing. We’re thankful to all of you for helping spread the word, sharing your knowledge, and supporting your fellow Kotlin developers. The warm, welcoming atmosphere you create is what makes exploring Kotlin together such a delightful experience. It wouldn’t be the same without you.

Kotlin 1.4 Online Event

We want to make sure that you have a great experience using Kotlin 1.4, and we want you to have a good idea of where we are taking the language next. This is why we are happy to invite all of you to our Kotlin 1.4 Online Event!

It consists of four days packed with knowledge about Kotlin and the future of the language and its ecosystem: We’ll discuss the new changes and improvements we made with Kotlin 1.4, and we’ll share our future plans for the language. Our Kotlin team members will answer your questions in daily Q&A sessions. Submit your questions in advance by tweeting them with the #kotlin14ask hashtag, or using this form.

The Kotlin 1.4 Online Event will be streamed on October 12–15, and you can register for free here:

Register for Kotlin 1.4 Online Event

We look forward to seeing all of you there!

Focusing on quality

Our main focus for this release was improving the overall development experience with Kotlin, including improved IDE performance and stability. Our goal is to make Kotlin users as productive as possible, and we focused on improving the things that are most important to users, so they feel even happier when using it!

We’ve reviewed and fixed more than 60 performance issues, including many that were causing IDE freezes or memory leaks. During the EAP phase for Kotlin 1.4.0, we gathered a lot of positive feedback indicating that the overall experience is now much more enjoyable!

When you are working with a project and open a large Kotlin file for the first time, you now see its content with highlighting much sooner. In most cases, highlighting is now 1.5-4 times faster:

We have also significantly improved the time it takes for autocomplete suggestions to appear. The following graph shows an overview of the average autocomplete response times that Kotlin users experience. The number of cases in which completion takes more than 500 ms has been cut nearly in half:

file

Note that these latest changes, including the code highlighting speed-up, require IntelliJ IDEA 2020.1+ and Android Studio 4.1+.

Performance improvements are an ongoing process, and we have many more enhancements planned, like continuing to work on eliminating freezing and making typing smoother. We’ve already started integration with the new experimental Kotlin compiler frontend that will make the IDE a lot faster. This is a huge task that requires many parts of the plugin to be rewritten, but it will boost performance in many areas of the IDE, including code completion, syntax highlighting, and compiler error reporting.

New IDE functionality

Our mission at JetBrains is to make software development a more productive and enjoyable experience, so we naturally want to make sure that the tooling surrounding Kotlin is excellent and makes coding Kotlin as easy as possible.

To make it easier for you to work with coroutines, and especially to pinpoint bugs in your concurrent applications, we’ve introduced the Coroutine Debugger. We’re going to expand on its initial feature set to provide the functionality most needed by the community, so please share your feedback with us using one of our channels or in the comments section below.

We are also introducing a new flexible Kotlin Project Wizard. This new wizard provides a single place for you to create and configure Kotlin projects of different types, making it easy to get started even with more complex structures such as multiplatform projects.

More than 40 new quick-fixes, intentions, and inspections have been added with Kotlin 1.4.0, and will be available exactly when you need them – when you modify your code, and press Alt+Enter to see what’s available in your specific context.

New compiler

For quite some time now, we’ve been working on a new Kotlin compiler that will advance the evolution of Kotlin in terms of performance and extensibility. The main goals for the new compiler are that it should be really fast, unify all the platforms that Kotlin supports, and provide an API for compiler extensions. We’re introducing new parts step by step, so that they reach the user as soon as possible. With Kotlin 1.4.0, we’re releasing several parts from this ongoing effort:

We’re actively working on a new frontend implementation, which will provide the biggest performance increase in the compiler pipeline. The frontend is the part of the compiler that parses the code, resolves names, performs type checking, and more, so it affects the IDE performance as well. A preview of it will be available in future releases, stay tuned!

Language features

Kotlin 1.4 comes with many new features:

Library improvements

Our general priority for the standard library is to improve consistency, both across different platforms and among the operations themselves. In this release, the Kotlin standard library gets new collection operators, delegated properties improvements, the double-ended queue implementation ArrayDeque, and much more.

You can use the standard library in “common” code – the code shared between different platforms, be they Android & iOS or JVM & JS. We’re gradually extending the common library and adding or moving missing functionality to it.

It is also no longer necessary to declare a dependency on the stdlib in any Gradle Kotlin project, whether you are targeting a single platform or working in a multiplatform project. Starting with Kotlin 1.4.0, this dependency is added by default.

We’re working on other parts of the Kotlin ecosystem:

Kotlin/JVM

We encourage you to try out the new Alpha Kotlin/JVM backend for your regular projects and share your feedback! Along with unifying the compiler pipelines, this effort will help us bring compiler extensions like Jetpack Compose to the Kotlin community more quickly.

Language features specific to Kotlin/JVM:

Kotlin/JS

Kotlin 1.4.0 comes with a new Gradle DSL and an Alpha version of the new Kotlin/JS compiler backend, among other features.

  • The new Gradle DSL adds support for configuring CSS and style loaders from the DSL, it includes various improvements related to npm dependency management and improves control over the Dukat integration.
  • The new Kotlin/JS compiler backend gives a taste of the future for Kotlin/JS. It includes optimizations and features such as the automatic generation of TypeScript definitions from Kotlin code, smaller binaries and bundles, a modernized way to expose Kotlin functionality to JavaScript, and more.

Kotlin/Native

Kotlin/Native got a significant number of new features and improvements, including:

The current automatic memory management implementation in Kotlin/Native has limitations when it comes to concurrency and we are working on a replacement for it.

An important focus for Kotlin/Native is making it seamless for Kotlin Multiplatform Mobile, but it’s not limited to this.

Kotlin Multiplatform

Making Kotlin a great multiplatform solution is one of our top priorities. We promised some important improvements at KotlinConf, and we’re happy to report on what we’ve delivered:

We’re working on an Android Studio plugin for running, testing, and debugging Kotlin code on iOS devices and simulators. The first public preview is going to be released very soon, so please stay tuned.

We’re soon going to release a bunch of materials created with the help of Kotlin community members explaining how you can use Kotlin Multiplatform Mobile (KMM) technology to target specifically mobile use-cases in which code is shared between Android and iOS.

Despite the major focus now being on mobile targets, the Web target for Kotlin Multiplatform is already actively used by JetBrains to build and ship JetBrains Space. Web target continues to be an important strategic investment for Kotlin.

More details

You can find detailed descriptions of new features on the Kotlin 1.4 What’s New page and documentation, and read more about migrating to Kotlin 1.4.

As in all major releases, some deprecation cycles of previously announced changes are coming to an end with Kotlin 1.4. All of these cases were carefully reviewed by the language committee and are listed in the Compatibility Guide for Kotlin 1.4.

How to help us improve Kotlin

The Kotlin plugin in IntelliJ IDEA and Android Studio can collect anonymized statistics about how you use its functionality. We kindly ask you to opt in to these statistics!

This anonymous data greatly helps us understand our users better, see what works, what is causing difficulties, and where we should direct our focus. To enable statistics, go to Preferences, open Appearance & Behaviour | System Settings | Data Sharing and activate the Send usage statistics checkbox.

Top issue reporters since Kotlin 1.3

We’d like to thank all the members of the community who helped us make this release better by reporting issues to YouTrack! We’ve made a list of the top 20 reporters and would like to thank them specifically:

Igor Wojda (145 issues); Louis CAD (87 issues); Marc Knaup (86 issues); AndroidDeveloperLB (83 issues); Robert Stoll (68 issues); Morgan Bartholomew (62 issues); Victor Turansky (54 issues); Guan Tianyi (51 issues); Scott Pierce (38 issues); Andreas Malik (37 issues); Steven Schäfer (37 issues); Björn Kautler (36 issues); Róbert Papp (34 issues); Toshiaki Kameyama (30 issues); Nicholas Bilyk (29 issues); Michael Bailey (26 issues); Jake Wharton (25 issues); Lamberto Basti (24 issues); Serge Pro (23 issues); Egor Andreevici (21 issues).

Start using Kotlin 1.4 right now

As always, you can try Kotlin online at play.kotl.in.

In Gradle and Maven, use 1.4.0 as the compiler version. See the docs for Gradle and for Maven.

IntelliJ IDEA and Android Studio automatically prompt you to update the Kotlin plugin to version 1.4.0. You can also open Preferences | Plugins and update the Kotlin plugin manually.

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

You can use the following versions of the libraries published together with this release:

The versions of libraries from kotlin-wrappers (kotlin-react etc.) can be found in the corresponding repository.

The latest IDE performance improvements, including the code highlighting speed-up, require IntelliJ IDEA 2020.1+ and Android Studio 4.1+.

If you run into any problems with the new release, you can find help on Slack (get an invite here) and report issues in our YouTrack.

Thank you!

We’re really grateful to everyone who has tried out and given us feedback on the Kotlin EAPs and experimental features. We are developing the Kotlin language together with you, and making many design decisions based on your invaluable input. Keeping this fast and effective feedback loop going with the community is really important to help Kotlin become the best it can be!

We want to say a big thank you to all our external contributors whose pull requests were included in this release. You helped us make this release happen!

We’re grateful to all members of our community who are creating so many amazing things with Kotlin. Kotlin 1.4: One for all!

Continue ReadingKotlin 1.4 Released with a Focus on Quality and Performance

End of content

No more pages to load