Tag Archives: Kotlin

KSP2 Preview: Kotlin K2 and Standalone Source Generator

Posted by Ting-Yuan Huang – Software Engineer, and Jiaxiang Chen – Software Engineer

The Kotlin Symbol Processing (KSP) tool provides a high-level API for doing meta-programming in Kotlin. Many tools have been built on KSP, enabling Kotlin code to be generated at compile time. For example, Jetpack Room uses KSP to generate code for accessing the database, based on an interface provided by the developer, like:

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll(): List<User>
}

KSP provides the API to the Kotlin code so that Room in this case can generate the actual implementation of that interface. While KSP has become a core foundation for meta-programing in Kotlin, its current implementation has some gaps which we are aiming to resolve with a new KSP2 architecture. This blog details those architectural changes and the impact for plugins built on KSP.

In addition, KSP2 has preview support for:

    • The new Kotlin compiler (code-named K2)
    • A new standalone source generator that provides more flexibility and features than the current Kotlin compiler plugin

After getting feedback on the new architecture and continuing to address gaps we will work towards releasing KSP 2.0 where these changes will be the default.

Enabling the KSP2 Preview

The new preview changes can be enabled in KSP 1.0.14 or newer using a flag in gradle.properties:

ksp.useKSP2=true

Note: You might need to enlarge the heap size of the Gradle daemon now that KSP and processors run in the Gradle daemon instead of the Kotlin compiler’s daemon (which has larger default heap size), e.g. org.gradle.jvmargs=-Xmx4096M -XX:MaxMetaspaceSize=1024m

KSP2 and K2

Internally KSP2 uses the Beta Kotlin K2 compiler (which will be the default compiler in Kotlin 2.0). You can use KSP2 before switching your Kotlin compiler to K2 (via the languageVersion setting) but if you want to use K2 for compiling your code, check out: Try the K2 compiler in your Android projects.

Standalone Source Generator

KSP1 is implemented as a Kotlin 1.x compiler plugin. Running KSP requires running the compiler and specifying KSP and its plugin options. In Gradle, KSP’s tasks are customized compilation tasks, which dispatch real work to KotlinCompileDaemon by default. This makes debugging and testing somewhat difficult, because KotlinCompileDaemon runs in its own process, outside of Gradle.

In KSP2, the implementation can be thought of as a library with a main entry point. Build systems and tools can call KSP with this entry point, without setting up the compiler. This makes it very easy to call KSP programmatically and is very useful especially for debugging and testing. With KSP2 you can set breakpoints in KSP processors without having to perform any other / irregular setup tasks to enable debugging.

Everything becomes much easier because KSP2 now controls its lifecycle and can be called as a standalone program or programmatically, like:

val kspConfig = KSPJvmConfig.Builder().apply {
  // All configurations happen here.
}.build()
val exitCode = KotlinSymbolProcessing(kspConfig, listOfProcessors, kspLoggerImpl).execute()

KSP2 API Behavior Changes

With the new implementation, it is also a great opportunity to introduce some refinements in the API behavior so that developers building on KSP will be more productive, have better debuggability and error recovery. For example, when resolving Map<String, NonExistentType>, KSP1 simply returns an error type. In KSP2, Map<String, ErrorType> will be returned instead. Here is a list of the current API behavior changes we plan on making in KSP2:

    1. Resolve implicit type from function call: val error = mutableMapOf<String, NonExistType>()
      KSP1: The whole type will be an error type due to failed type resolution
      KSP2: It will successfully resolve the container type, and for the non-existent type in the type argument, it will correctly report errors on the specific type argument.
    2. Unbounded type parameter
      KSP1: No bounds
      KSP2: An upper bound of Any? is always inserted for consistency
    3. Resolving references to type aliases in function types and annotations
      KSP1: Expanded to the underlying, non-alias type
      KSP2: Not expanded, like uses in other places.
    4. Fully qualified names
      KSP1: Constructors have FQN if the constructor is from source, but not if the constructor is from a library.
      KSP2: Constructors do not have FQN
    5. Type arguments of inner types
      KSP1: Inner types has arguments from outer types
      KSP2: Inner types has no arguments from outer types
    6. Type arguments of star projections
      KSP1: Star projections have type arguments that are expanded to the effective variances according to the declaration sites.
      KSP2: No expansion. Star projections have nulls in their type arguments.
    7. Variance of Java Array
      KSP1: Java Array has a invariant upper bound
      KSP2: Java Array has a covariant upper bound
    8. Enum entries
      KSP1: An enum entry has its own subtype with a supertype of the enum class (incorrect behavior from language point of view)
      KSP2: An enum entry's type is the type of the enclosing enum class
    9. Multi-override scenario

      For example
      interface GrandBaseInterface1 {
          fun foo(): Unit
      }
      
      interface GrandBaseInterface2 {
          fun foo(): Unit
      }
      
      interface BaseInterface1 : GrandBaseInterface1 {
      }
      
      interface BaseInterface2 : GrandBaseInterface2 {
      }
      
      class OverrideOrder1 : BaseInterface1, GrandBaseInterface2 {
          override fun foo() = TODO()
      }
      class OverrideOrder2 : BaseInterface2, GrandBaseInterface1 {
          override fun foo() = TODO()
      }
      

      KSP1:
      Find overridden symbols in BFS order, first super type found on direct super type list that contains overridden symbol is returned For the example, KSP will say OverrideOrder1.foo() overrides GrandBaseInterface2.foo() and OverrideOrder2.foo() overrides GrandBaseInterface1.foo()
      KSP2:
      DFS order, first super type found overridden symbols (with recursive super type look up) in direct super type list is returned.
      For the example, KSP will say OverrideOrder1.foo() overrides GrandBaseInterface1.foo() and OverrideOrder2.foo() overrides GrandBaseInterface2.foo()
    10. Java modifier
      KSP1: Transient/volatile fields are final by default
      KSP2: Transient/volatile fields are open by default
    11. Type annotations
      KSP1: Type annotations on a type argument is only reflected on the type argument symbol
      KSP2: Type annotations on a type argument now present in the resolved type as well
    12. vararg parameters
      KSP1: Considered an Array type
      KSP2: Not considered an Array type
    13. Synthesized members of Enums
      KSP1: values and valueOf are missing if the enum is defined in Kotlin sources
      KSP2: values and valueOf are always present
    14. Synthesized members of data classes
      KSP1: componentN and copy are missing if the data class is defined in Kotlin sources
      KSP2: componentN and copy are always present

New Multiplatform Processing Scheme

When it comes to the processing scheme, i.e. what sources are processed when, the principle of KSP is to be consistent with the build's existing compilation scheme. In other words, what the compiler sees is what processors see, plus the source code that is generated by processors.

What processors see Kotlin compiler see

ClassA.kt, UtilB.kt, InterfaceC.kt ... ClassA.kt, UtilB.kt, InterfaceC.kt ... + GeneratedFromA.kt, ...

In KSP1's current compilation scheme, common / shared source sets are processed and compiled multiple times, with each target. For example, commonMain is processed and compiled 3 times in the following project layout. Being able to process all the sources from dependencies is convenient with one exception: Processors don’t see the sources generated from commonMain when processing jvmMain and jsMain. Everything must be re-processed and that can be inefficient.

Flow diagram illustrating sources generated from jvmMain and jsMain processing to commonMain

tasks

inputs

outputs

kspKotlinCommonMainMetadata

commonMain

generatedCommon

kspKotlinJvm

commonMain, jvmMain

generatedCommonJvm

kspKotlinJs

commonMain, jsMain

generatedCommonJs

compileKotlinCommonMainMetadata

commonaMain, generatedCommon

common.klib

compileKotlinJvm

commonMain, jvmMain, generatedCommonJvm

app.jar

compileKotlinJs

commonMain, jsMain, generatedCommonJs

main.js

In KSP2, we plan to add an experimental mode that tries to align to how source sets are compiled in K2 better. All sources can be processed only once with the available new processing scheme:

tasks

inputs

outputs

Resolvable but not available in 

getAllFiles / 

getSymbolsWithAnnotation

kspKotlinCommonMainMetadata

commonMain

generatedCommon


kspKotlinJvm

jvmMain

generatedJvm

commonMain, generatedCommon

kspKotlinJs

jsMain

generatedJs

commonaMain, generatedCommon

compileKotlinCommonMainMetadata

commonaMain, generatedCommon

common.klib


compileKotlinJvm

commonMain, jvmMain, generatedCommon, generatedJvm

app.jar


compileKotlinJs

commonMain, jsMain, generatedCommon, generatedJs

main.js


Please note that Kotlin 2.0 is still in beta and the compilation model is subject to change. Please let us know how this works for you and give us feedback.

KSP2 Preview Feedback

KSP2 is in preview but there is still more work to be done before a stable release. We hope these new features will ultimately help you be more productive when using KSP! Please provide us with your feedback so we can make these improvements awesome as they progress towards being stable.

Bringing Kotlin to the Web

Posted by Vivek Sekhar, Product Manager

This post describes early experimental work from JetBrains and Google. You can learn more in the session on WebAssembly at Google I/O 2023.

Application developers want to reach as many users on as many platforms as they can. Until now, that goal has meant building an app on each of Android, iOS and the Web, as well as building the backend servers and infrastructure to power them.

Image showing infrastructure of Web, Android, and iOS Apps in relation to backend servers and programming support - JavaScript, Kotlin, and Swift respectively

To reduce effort, some developers use multiplatform languages and frameworks to develop their app's business logic and UI. Bringing these multiplatform apps to the Web has previously meant "compiling" shared application code to a slower JavaScript version that can run in the browser. Instead, developers often rewrite their apps in JavaScript, or simply direct Web users to download their native mobile apps.

The Web community is developing a better alternative: direct Web support for modern languages thanks to a new technology called WebAssembly GC. This new Web feature allows cross-platform code written in supported languages to run with near-native performance inside all major browsers.

We're excited to roll-out experimental support for this new capability on the Web for Kotlin, unlocking new code sharing opportunities with faster performance for Android and Web developers.


Kotlin Multiplatform Development on the Web

Kotlin is a productive and powerful language used in 95% of the top 1,000 Android apps. Developers say they are more productive and produce fewer bugs after switching to Kotlin.

The Kotlin Multiplatform Mobile and Compose Multiplatform frameworks from JetBrains help developers share code between their Android and iOS apps. These frameworks now offer experimental support for Kotlin compilation to WebAssembly. Early experiments indicate Kotlin code runs up to 2x faster on the Web using WebAssembly instead of JavaScript.

Image showing infrastructure of Web, Android, and iOS Apps in relation to backend servers and programming support - JavaScript, Kotlin, and Swift respectively

JetBrains shares more details in the release notes for version 1.18.20 of their K2 compiler, as well as documentation on how you can try Kotlin/Wasm with your app.


Pulling it off

Bringing modern mobile languages like Kotlin to the Web required solving challenging technical problems like multi-language garbage collection and JavaScript interoperability. You can learn more in the session on new WebAssembly languages from this year's Google I/O conference.

This work wouldn't have been possible without an open collaboration between browser vendors, academics, and service providers across the Web as part of the W3C WebAssembly Community Group. In the coming weeks, we'll share technical details about this innovative work on the V8 Blog.


Looking ahead: Web and Native Development

For decades, developers have dreamed of the Web as a kind of "universal runtime," while at the same time acknowledging certain feature or performance gaps relative to native platforms. Developers have long had to switch between working on the Web or their native mobile apps.

However, we want to make it possible for you to work on the Web and your native experiences together, not only to help you reduce effort, but also to help you tap into the Web's unique superpowers.

On the open web, your app is just a click away from new users, who can discover it and share it just as easily as they share a web page, with no app stores getting in the way and no revenue split affecting your profitability.

The productivity of cross-platform development, the performance of native mobile apps and the openness of the web. That's why we love WebAssembly.

We can't wait to see what you build next!


"The productivity of cross-platform development, the performance of native mobile apps, and the openness of the Web."

Kotlin DSL is Now the Default for New Gradle Builds

Posted by James Ward, Product Manager, Kotlin and Boris Farber, Developer Relations Engineer

Android has been Kotlin-first for four years and many Android developers have made the switch resulting in higher productivity and more stable apps. However the default language to define builds has been Groovy (build.gradle), even though a Kotlin (build.gradle.kts) option has existed in Gradle for a number of years.

Today we're excited to announce that we're switching the default language for build scripts to Kotlin! This means that Kotlin is the single default language used for all project code, including UI with Jetpack Compose, and now build scripts! We've been working with the Gradle and JetBrains teams on this improvement, and you can read more in their related announcements: Gradle Blog; JetBrains Blog.

This doesn’t affect existing projects using Groovy, as those will continue working with no plans for deprecation. But if you are creating new projects or modules starting from Android Studio Giraffe, you now get the Kotlin DSL by default. The updated project templates are an easy way to get started with the new Kotlin DSL build scripts. To migrate existing builds, check out the Kotlin DSL migration guide.

While the Kotlin DSL is the default for new projects, large, existing Groovy DSL based projects should wait on migrating while Gradle, JetBrains, and Google work on improving build performance further. This work is ongoing and we will share updates as we make progress. Specifically, script compilation performance is slower than with the Groovy DSL. However, unlike with the Groovy DSL, the Kotlin DSL script compilation results are stored in Gradle local and remote caches so that subsequent builds do not need recompilation.

Having a single language for all code in a project isn't the only benefit to this change, so let's look at some other great things about using the Kotlin DSL for Gradle builds.

  • Kotlin is statically typed so you get quick and accurate code hints while editing Kotlin DSL build scripts:
  • Syntax errors are more accurate, and they’re displayed while editing Kotlin DSL build scripts, instead of when trying to sync the project:
  • Get type and method documentation by pressing Control+Q (Command+B on macOS).If you need more details you can go to the underlying source code by pressing Control+Click (Command+Click):
  • You can mix Groovy DSL build scripts and Kotlin DSL build scripts in one project and migrate incrementally module by module. This enables new modules to use the Kotlin DSL while keeping existing modules on Groovy.

An associated change we are also making to the New Project templates is an experimental option to use Gradle Version Catalogs with Kotlin DSL build scripts.

Version Catalogs give you a centralized, scalable way of defining your project’s dependencies. While using Version Catalogs is optional, they pair great with the Kotlin DSL by providing more type safety in your build definitions.

To learn about migrating to Version Catalogs, check out the migration guide.

The new Kotlin DSL default change is available now in Android Studio Giraffe previews. Please try it and let us know how it goes!

Google at KotlinConf ‘23

Posted by Márton Braun, Developer Relations Engineer

As part of Google’s ongoing commitment to supporting the Kotlin language, we are really excited to be a gold level sponsor for KotlinConf again this year. Grace Kloba shared the story of Google’s investments in Kotlin within the keynote, which is recapped in this post. You’ll also find the list of talks by Google from the event’s schedule below, make sure you catch these on the live stream.

For a summary of all KotlinConf keynote announcements, read the blog post by JetBrains.

Kotlin for Android

Kotlin started gaining popularity in the Android community around 2016. We were also impressed with Kotlin’s concise syntax, modern features, and safety. In 2017, we announced official support for Kotlin on Android, and committed to its future by creating the Kotlin Foundation with JetBrains.

Since then we invested in Kotlin by adding support in Android Studio, teaching the language to developers, and going Kotlin-first with our libraries, documentation, and samples. We also built Kotlin Symbol Processing, an API that enables annotation processors to run up to twice as fast as previous solutions.

Today, Kotlin is the most popular language for Android development. Over 95% of the top 1000 Android apps use Kotlin, and over 50% of professional Android developers use Kotlin as their primary language (compared with 25% choosing the Java programming language).

Among professional Android developers using Kotlin, we saw a 96.9% positive satisfaction rate in our latest annual survey, which is 9-points higher than their Java counterparts.

As our final step in making Kotlin the single language for Android development, we’re excited to announce today that the Gradle Kotlin DSL is becoming the default build language for Android apps, starting in Android Studio Giraffe. Read the blog post to learn more.

Jetpack Compose

Since going Kotlin-first, all new Jetpack libraries are written in Kotlin. Jetpack Compose, our modern toolkit for building Android apps, is Kotlin-only. It makes extensive use of Kotlin’s language features, and its implementation is made possible by Kotlin’s rich compiler API, which allows us to generate state management logic for you.

Jetpack Compose is changing the way developers build apps. The team from Clue shared with us that their development speed increased up to 3x after rewriting their app in Compose. Over 23% of the top 1000 Android apps ship with Compose, more than double year over year.

There are many resources available to learn Compose. For existing Android developers looking to expand their knowledge, we’ve published the Jetpack Compose for Android Developers course. For beginners to programming, we recommend taking the Android Basics with Compose course to learn Kotlin, Android, and Compose.

Kotlin at Google

Kotlin became generally available for Android development within Google in 2019. Since then, most of our Android apps are being built with Kotlin. As an example of the benefits, when the Google Home team migrated to Kotlin they saw a 33% decrease in NullPointerExceptions, which greatly improved the end user experience.

However, Google’s interest in Kotlin does not stop at Android apps. More than 45% of our engineers who write Kotlin use it for server development. We have over 15 million lines of Kotlin code in Google’s source control system, and this has been doubling year over year.

To support this, we have a dedicated team building tools to integrate Kotlin into Google’s ecosystem. You can catch the Adopting Kotlin at Google scale session for more details.

We’re looking forward to the new compiler in Kotlin 2.0, which will be a major improvement for developer productivity. We have a dedicated team working with JetBrains on the compiler, and we’re working to incorporate it into our tooling, including Android Studio, KSP, and the Compose compiler. We’re also leveraging our large internal codebase of Kotlin code to verify the compatibility of the new compiler.

Multiplatform

Looking forward, we are experimenting with Kotlin Multiplatform. This includes the Google Workspace team, who have a prototype with the business logic of Google Docs running on iOS using Kotlin Multiplatform and Kotlin/Native. Check out the Kotlin Multiplatform in Google Workspace lightning talk to learn more.

As part of our explorations into Kotlin Multiplatform, we’ve also made contributions that will benefit the community:

  • We’ve ported a set of Jetpack libraries to multiplatform. This allows you to use tools and APIs you know and love from Android and apply them to multiplatform. 
  • We’ve contributed to the Kotlin/Native toolchain, improving its performance. 
  • We’ve been helping out with the Gradle plugin for Kotlin Multiplatform, to give you more control over each target platform while still sharing as much code as possible.

Kotlin Foundation

As a founding member of the Kotlin Foundation, we’re excited about the Foundation’s expansions announced at KotlinConf:

  • Inviting more companies to collaborate on the development and promotion of Kotlin through a membership program
  • Offering funding for individual authors of actively maintained, open source Kotlin Multiplatform libraries.

With these steps, we continue to foster a healthy ecosystem for the language, and ensure its future advancement.

Catch us at KotlinConf

We look forward to sharing more in our sessions at KotlinConf, which you can tune in to on the live stream. If you’re attending in person, you can also visit us at our booth to have a chat about Kotlin.

April 13 schedule

Adopting Kotlin at Google scale
Jeffrey van Gogh, John Pampuch

Spring + Kotlin = Modern + Reactive + Productive
Josh Long, James Ward

Kotlin Multiplatform in Google Workspace
Jason Parachoniak

Kotlin Multiplatform Conversions at Android Jetpack Scale
Dustin Lam, James Ward

Untangling Coroutine Testing
Márton Braun

Adventures building a Kotlin Multiplatform Benchmarking Library
Rahul Ravikumar

April 14 schedule

Tracing coroutines in the JVM
Tyson Henning

Preventing Data Races in Async Coroutines
Kevin Bierhoff

Avoiding common coroutines mistakes in Compose
Márton Braun

*Java is a trademark or registered trademark of Oracle and/or its affiliates.

Interview with Top Kotlin Contributors – Highlighting their Contributions to the Google Dev Library

Posted by Swathi Dharshna Subbaraj, Project Coordinator, Google Dev Library

In May 2017, Google recognized the potential of Kotlin in the mobile developer community and made it an official language for Android development. As a result, talented developers in the Kotlin community used this robust programming language to build inspiring tools and open-source projects. This can be seen in the Google Dev Library, where developers have contributed extensively.

This article will showcase some of our Kotlin Google Developer Experts (GDEs) who have made significant contributions to the Google Dev Library. We hope these projects will inspire and guide your development efforts.
 

Contributors in Spotlight :


Nicola Corti

Nicola contributed Detekt to Google Dev Library, which is a static code analysis tool for Kotlin projects that helps developers detect and report on issues related to security, style, and best practices. It can be used to identify potential vulnerabilities, enforce coding standards, and improve code quality.

How did you get started in Kotlin? Is there any particular project that inspired you?

I began working with Kotlin in its early days of 2015. Though the experience was rocky, the ability to code Android apps in Kotlin rather than Java was a game-changer. At the time, it was challenging to convince my colleagues to switch due to the Java-dominant community. However, the official announcement of Kotlin support at Google I/O 2017 was a defining moment for the language. I am grateful for the ongoing support and development of such a powerful and versatile language, as well as the dedicated community that supports it daily.

I am grateful for the ongoing support and development of such a powerful and versatile language, and the dedicated community that supports it daily. Nicola Corti, GDE Kotlin 

What inspired you to inherit the Detekt project ?

Detekt, a static code analyzer tool, is not a creation of mine, but rather a project that I inherited from a friend who sought support in managing it. I have always been impressed by the capabilities of static code analyzers, particularly in terms of their ability to detect bugs and save developer time. At the time, the market for Kotlin static analyzers was relatively new, making Detekt a valuable addition to the toolkits of many Kotlin developers.

As a Kotlin GDE, what is the one piece of advice for someone who has just started as a Kotlin developer?

I highly recommend getting involved in the open-source community. My contributions to open-source projects have taught me invaluable skills and knowledge that I wouldn't have gained otherwise. Additionally, I have had the opportunity to connect with incredible contributors who have since become friends. Participating in open-source not only benefits yourself, but also the wider developer community.

John O'Reilly

John created the PeopleInSpace project, and shared it with Google Dev Library. The project utilizes the OpenNotify API to display information about people currently in space, such as their names, nationalities, and spacecraft. The focus of the project is more about demonstrating use of Kotlin Multiplatform.

How did you get started in Kotlin? Is there any particular project that inspired you?
In 2010, I began my career as an Android developer, utilizing Java as my primary programming language. As a Java backend developer for the previous decade, the transition was relatively seamless. However, it wasn't until the official announcement of Kotlin support at Google I/O 2017, that I fully realized the potential impact of this new programming language. Gradually, as my team and I started migrating to Kotlin, I came to appreciate how productive and expressive a language it was to use.

As my team and I started migrating to Kotlin, I came to appreciate how productive and expressive a language it was to use.  - John O'Reilly, GDE Kotlin

What inspired you to develop and open source the Peopleinspace project?

In 2018, I was introduced to Kotlin Multiplatform (KMP) and was immediately impressed by its practical and efficient approach to code sharing. At the time, there was still a lot of uncertainty and confusion surrounding KMP, and I saw a need for a simple, easy-to-understand sample project that could demonstrate the basics of KMP.

I had an existing open-source project, GalwayBus, which I initially used to experiment with KMP, Jetpack Compose and SwiftUI as they became available. However, this project had a significant amount of legacy code and was not ideal for showcasing the essentials of KMP.

In late 2019, I came across an article by Ken Kousen that included sample code using retrofit to retrieve a list of people in space. I realized that this could be the perfect foundation for the minimal project I had been envisioning. So, I created PeopleInSpace, a project designed to encapsulate the core elements of a KMP project, and provide a clear and concise demonstration of how the various components work together.

As a Kotlin GDE, what is the one piece of advice for someone who has just started as a Kotlin developer?

Kotlin is a powerful language that offers many advanced features; however, it is possible to be very productive when starting out without needing to use those, in many cases, there are simpler alternatives that can be used, and as you become more familiar with the language, you can gradually explore and implement the more advanced options.

Join the global community of Kotlin developers and share your open source projects or technical blogs on Dev Library. To contribute, submit your content here.

How to learn Kotlin: JetBrains, the company behind the Kotlin language, offers certificate courses and learning tools for developers and has an active user groups forum where developers get support with programming language-related issues.

Google Cloud & Kotlin GDE Kevin Davin helps others learn in the face of challenges

Posted by Kevin Hernandez, , Developer Relations Community Manager

Kevin Davin speaking at the SnowCamp Conference in 2019

Kevin Davin has always had a passion for learning and helping others learn, no matter their background or unique challenges they may face. He explains, “I want to learn something new every day, I want to help others learn, and I’m addicted to learning.” This mantra is evident in everything he does from giving talks at numerous conferences to helping people from underrepresented groups overcome imposter syndrome and even helping them become GDEs. In addition to learning, Kevin is also passionate about diversity and inclusion efforts, partly inspired by navigating the world with partial blindness.

Kevin has been a professional programmer for 10 years now and has been in the field of Computer Science for about 20 years. Through the years, he has emphasized the importance of learning how and where to learn. For example, while he learned a lot while he was studying at a university, he was able to learn just as much through his colleagues. In fact, it was through his colleagues that he picked up lessons in teamwork and the ability to learn from people with different points of view and experience. Since he was able to learn so much from those around him, Kevin also wanted to pay it forward and started volunteering at a school for people with disabilities. Guided by the Departmental Centers for People with Disabilities, the aim of the program is to teach coding languages and reintegrate students into a technical profession. During his time at this center, Kevin helped students practice what they learned and ultimately successfully transition into a new career.

During these experiences, Kevin was always involved in the developer community through open-source projects. It was through these projects that he learned about the GDE program and was connected to Google Developer advocates. Kevin was drawn to the GDE program because he wanted to share his knowledge with others and have direct access to Google in order to become an advocate on behalf of developers. In 2016, he discovered Kubernetes and helped his company at the time move to Google Cloud. He always felt like this model was the right solution and invested a lot of time to learn it and practice it. “Google Cloud is made for developers. It’s like a Lego set because you can take the parts you want and put it together,” he remarked.

The GDE program has given him access to the things he values most: being a part of a developer community, being an advocate for developers, helping people from all backgrounds feel included, and above all, an opportunity to learn something new every day. Kevin’s parting advice for hopeful GDEs is: “Even if you can’t reach the goal of being a GDE now, you can always get accepted in the future. Don’t be afraid to fail because without failure, you won’t learn anything.” With his involvement in the program, Kevin hopes to continue connecting with the developer community and learning while supporting diversity efforts.

Learn more about Kevin on Twitter & LinkedIn.

The Google Developer Experts (GDE) program is a global network of highly experienced technology experts, influencers, and thought leaders who actively support developers, companies, and tech communities by speaking at events and publishing content.

Celebrating 5 years of Kotlin on Android

Posted by Márton Braun, Developer Relations Engineer

Five years ago, at the 2017 Google I/O Keynote, we did something we had never done before: we announced official support for a new programming language to build Android apps with: Kotlin. It was great to see how excited the Android developer community was about this announcement.


Since then, JetBrains and Google have been collaborating around the development of Kotlin, and the Kotlin Foundation was co-founded by the two companies.

As highlighted in those initial I/O announcements, Kotlin is interoperable, mature, production-ready, and open source. It also has outstanding IDE support, as JetBrains develops both the language and its tooling.

Now, five years have passed since the original announcement. To celebrate the amazing language that now powers modern Android app development, we’re taking a quick look at the journey of Kotlin on Android. This post includes quotes from a handful of people who were involved in making Kotlin on Android a success, who are joining us for this celebration.

Early years

The Kotlin adoption story started before official support from Google, within the Android developer community. The excitement in the community was one of the main reasons to invest in official support.
“The decision by Google to add support for Kotlin, I think we underestimate how wild of a notion that was at the time. The odds of another company that size making a similar decision based on community support and enthusiasm is very low.“ (Christina Lee, Android engineer at Pinterest, Kotlin and Android GDE)

After the 2017 announcement, Android Studio started shipping with built-in support for Kotlin. Lots of documentation and samples were updated to use Kotlin.

In 2018, we launched the Android KTX libraries, which provide Kotlin-friendly extensions wrapping the APIs of the Android framework and several AndroidX libraries. Tooling improved further, too, with Kotlin-specific live templates, lint checks, and optimizations in R8 and ART. The reference documentation for Android was also published in Kotlin for the first time.


Going Kotlin-first

At Google I/O 2019, we committed to Kotlin-first Android development, further increasing our investments in the language.
“If you look at a Kotlin new users graph, you immediately notice the two most significant spikes – one in May 2017 and another in May 2019. We have an inside joke about it: ‘Marketing a programming language is easy. All you have to do is make the largest operating system in the world call it an official language during the annual keynote’” (Egor Tolstoy, Kotlin Product Lead at JetBrains)

Being Kotlin-first means that we now design our documentation, samples, training content, new libraries and tools for the Kotlin language first, while still supporting users of the Java programming language.

”Now when we want to start a Jetpack Library, we are writing it in Kotlin unless we have a very, very, very good reason not to do that. It’s clear that Kotlin is the first-class language.” (Yigit Boyar, early proponent of Kotlin within Google, currently leading the development of a handful of Jetpack libraries)


Some examples of Kotlin-first Jetpack libraries are Paging 3 and DataStore, which are both powered by coroutines and Flows for asynchronous operations.


Jetpack Compose, Android’s modern UI toolkit is our greatest commitment to Kotlin so far, as it’s Kotlin-only. It’s powered by a Kotlin compiler plugin, and it makes extensive use of advanced language features like coroutines, top-level functions, and trailing lambdas.

“Kotlin is here to stay and Compose is our bet for the future. Right now, for developers that are starting to learn Android, we’re already recommending the Android Basics with Compose course.” (Florina Muntenescu, Jetpack Compose developer relations lead)


Kotlin beyond Android

Even though Kotlin is a great fit for Android, it’s a general-purpose language and not solely for use on Android. For teams within Google, Kotlin is now generally available to use for both Android and server-side projects. Thousands of Google engineers are writing Kotlin code, and our internal codebase contains more than 8.5 million lines of Kotlin code to date. This number has been increasing rapidly as well, doubling year over year.
“We’ve been working to bring Kotlin to Google engineers for the last few years by adding Kotlin support to all the tools they use. This includes the build system, static analysis tools, libraries and APIs. We’ve talked a lot about encouraging developers to use Kotlin for Android app development, and we strongly encourage using Kotlin for server-side development as well.” (Kevin Bierhoff, lead of the Kotlin at Google team, which supports Google engineers writing Kotlin code)

gRPC Kotlin and Kotlin for protocol buffers are examples of Kotlin projects Google uses both in Android apps and on servers that have been open sourced and are now receiving community adoption and contributions. Kotlin is also supported on Google Cloud.


Collaboration with JetBrains

There is close collaboration between JetBrains and Google around the development of Kotlin. The Kotlin Foundation was co-founded by the two companies, and it ensures that the language and ecosystem age well.

Google engineers have also been working on improving the compiler and on creating important tooling for the language.
“My team is helping JetBrains with rewriting the Kotlin compiler right now, and we also work on Kotlin Symbol Processing, which is the first compiler-related Kotlin project that’s been completely done at Google. We work more closely with JetBrains than some other parts of Google." (Jeffrey van Gogh, member of the Kotlin Foundation, lead of the Kotlin engineering team at Google)

JetBrains and Google also coordinate new releases of the language and the accompanying tooling so that developers are able to use the latest releases as smoothly as possible.
“The collaboration gets stronger over time, and I’m really excited to see its impact on Kotlin’s future. Our coordinated pre-release checks are getting better and better." (Liliia Abdulina, Kotlin QA team lead at JetBrains)


Learn more and share your own stories

You can read more stories about Kotlin from our interviewees in the accompanying Medium post. We’d also love to hear your stories of learning and adopting Kotlin for Android development! Share them on social media using the hashtag #Hi5KotlinOnAndroid!

Finally, let’s appreciate these kind words about Kotlin’s accomplishments to conclude our story.

“Technology can really change people's lives and it can really make people happier at work. We normally focus on ‘there's null safety’ or ‘there's type inference’ or all these other technical parts. But when you take a step back, there's a whole story in there about all of the people who had their passion for coding ignited or reignited because Kotlin is such a wonderful language. It's just so impressive that the team is able to do what they're able to do and that the community is as good as it is." (Christina Lee, Android engineer at Pinterest, GDE for Android and Kotlin)

Have a nice Kotlin on Android!

*Java is a trademark or registered trademark of Oracle and/or its affiliates.

Discontinuing Kotlin synthetics for views

Posted by Márton Braun, Developer Relations Engineer


ALT TEXT GOES HERE 

Synthetic properties to access views were created as a way to eliminate the common boilerplate of findViewById calls. These synthetics are provided by JetBrains in the Kotlin Android Extensions Gradle plugin (not to be confused with Android KTX).

In November 2020, we announced that this plugin has been deprecated in favor of better solutions, and we recommended removing the plugin from your projects. We know many developers still depend on this plugin’s features, and we’ve extended the support timeframe so you have more time to complete your migrations.

We are now setting a deadline for these migrations: the plugin will be removed in Kotlin 1.8, which is expected to be released by the end of 2022. At that time, you won’t be able to update your project to newer Kotlin versions if it still depends on the Kotlin Android Extensions plugin. This means that now is the time to perform the necessary migrations in your projects.

Instead of synthetics, we recommend using View Binding, which generates type-safe binding classes from XML layout files. These bindings provide convenient access to view references and they work safely for layouts with multiple configurations. See the migration guide for detailed instructions on how to adopt View Binding. If you encounter any issues, you can report a bug on the Issue Tracker.

When building new features, consider using Jetpack Compose, Android's modern UI toolkit. Layouts built with Compose are declarative Kotlin code, eliminating the need to work with view references.

Another feature included in the plugin is Parcelize, which helps you create parcelable classes. Parcelize is now available in the standalone kotlin-parcelize plugin with unchanged functionality. To get up and running with the new plugin, check out the Parcelize documentation page.

If you’re still using the Kotlin Android Extensions Gradle plugin, kick off your migration in time so that you can keep upgrading to new Kotlin releases in the future. This will enable you to use the latest language features and take advantage of tooling and compiler improvements.

Android Basics and Training Update

Posted by Dan Galpin, Developer Relations Engineer

Android robot on a pretend video call

In October of 2021 we released the final unit of Android Basics in Kotlin, our free, self-paced programming course that makes Android development accessible to everyone. It teaches people with no programming experience how to build Android apps. Along the way, students learn the fundamentals of programming and the basics of the Kotlin programming language.

In response to feedback from educators and learners, we've continued to iterate on our course material, adding projects that allow you to apply learnings along with new topics that can prepare students for more advanced material.

A focus on basics

With these updates, Android Basics in Kotlin now covers the key material covered in Android Kotlin Fundamentals, so we will be sunsetting the latter course. More advanced learners are encouraged to work through the Basics material, skipping sections that they are familiar with and moving straight to quizzes. Focusing on basics means that intermediate and advanced learners that might be missing a key concept will have what they need to succeed with this material. This also allows our team to focus on making sure our courseware continues to represent our most recent guidance. In addition to courseware, we're continuing to provide codelabs, code samples, documentation, and video content to serve learners at all levels.

What's next?

Our team is hard at work on the next course that will teach people how to program Android applications using Jetpack Compose. We're looking forward to teaching Android’s modern toolkit for building native UI because of all the ways that it simplifies and accelerates Android UI development.

What to do now

Taking the current course will teach you the fundamentals of app development, serving as a great starting point should you want to explore the existing Jetpack Compose Learning Pathway, or jump into the upcoming Android Basics with Compose course. You'll have a foundation that you can build on as you continue to explore the world of Android development. Both versions of Android Basics are planned to coexist, giving the option of learning Android with either UI toolkit.

Whether you’ve never built an app before but want to learn how, or just want to brush up on some of our latest best practices, check out the Android Basics in Kotlin course.

Announcing Kotlin support for protocol buffers

Posted by Deanna Garcia and Louis Wasserman - Software Developers, and Developer Advocate, James Ward

Google’s commitment to Kotlin

At Google, we’re investing deeply in the Kotlin language and ecosystem. Android development is now Kotlin first, our engineering teams work on language evolution through the Kotlin Foundation, and inside of Google we’re using Kotlin more and more to build our backend services. We love Kotlin for its expressiveness, safety, simple async support through coroutines, and easy bidirectional interoperability with the Java programming language.

Kotlin for protocol buffers

Last year, we open sourced Kotlin support for gRPC, the open source Remote Procedure Call (RPC) framework that powers thousands of microservices at Google. We’re excited to deepen our investment in the Kotlin language with official support for Kotlin in the open source Protocol Buffers project (a.k.a. “protos”), Google’s platform-neutral, high-performance data interchange format. From a proto definition, you can use the new built-in Kotlin support in the proto compiler to generate idiomatic Kotlin Domain Specific Languages (DSLs).

For example, here’s a simple protocol buffer message representing a series of dice rolls:

message DiceSeries {
message DiceRoll {
int32 value = 1; // value of this roll, e.g. 2..12
string nickname = 2; // string nickname, e.g. "snake eyes"
}

repeated DiceRoll rolls = 1;
}

In the Java language, constructing a series of dice rolls might look like this:

DiceSeries series = DiceSeries.newBuilder()
.addRoll(DiceRoll.newBuilder()
.setValue(5))
.addRoll(DiceRoll.newBuilder()
.setValue(20)
.setNickname("critical hit"))
.build()

With this release, protos offer an expressive set of DSL factory methods that make this code elegant and idiomatic in Kotlin. Here is the equivalent dice roll code written using the new Kotlin proto bindings:

val series = diceSeries {
rolls = listOf(
diceRoll { value = 5 },
diceRoll {
value = 20
nickname = "critical hit"
}
)
}

The Kotlin version uses Kotlin type-safe builders, which makes it concise and removes the need to explicitly call a build method. Note that this works with both the proto compiler’s standard and "proto lite" modes, the latter generating smaller, higher performance classes which are more suitable for Android.

Note: Since protos use the get prefix for their fields and Kotlin recognizes that as a property, reading from a proto already works smoothly from Kotlin as if the proto were a data class.

val totalRolls = series.rolls.map { it.value }.sum() // 5 + 20 = 25

Kotlin Protos and gRPC Kotlin

The new Kotlin Protos work great with gRPC Kotlin providing a concise syntax for messages and services. Let's walk through a basic sample.

Here is a basic "Greeter" gRPC service proto:

service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}

Check out the full example proto source.

The non-blocking server can be implemented concisely, taking advantage of the Kotlin proto builders:

class HelloWorldService : GreeterCoroutineImplBase() {
override suspend fun sayHello(request: HelloRequest) = helloReply {
message = "hello, ${request.name}"
}
}

Check out the full example server source.

The non-blocking client also can take advantage of the type-safe Kotlin builders with concise syntax:

val stub = GreeterCoroutineStub(channel)
val request = helloRequest { name = "world" }
val response = stub.sayHello(request)
println("Received: ${response.message}")

Check out the full example client source.

Those code examples really illustrate how concise the syntax is, which means less boilerplate to write and less for our brains to parse as we try to read the code. What isn't evident in these examples is how nice the experience is when writing high-performance RPC code. Thanks to static typing and the type-safe builders, you can easily code-complete your way through code that is "correct" in-that the types / properties are consistent with the protos.

The protobuf compiler (protoc) now has built-in support for generating Kotlin code. A bit of configuration is needed to tell your build tool (Maven, Gradle, etc) to do that. For Gradle builds it looks like:

protobuf {
// omitted protoc and plugins config
generateProtoTasks {
all().forEach {
// omitted plugins config
it.builtins {
id("kotlin")
}
}
}
}

Check out the full example Gradle build.

Give the complete gRPC Kotlin example a spin and also explore other aspects like the Android client and native client (built with GraalVM Native Image) which both use the lite protos. For an example Maven project check out the grpc-hello-world-mvn sample.

For examples that can be deployed with a couple clicks on Google Cloud Run (a fully managed serverless platform) check out: grpc-hello-world-gradle, grpc-hello-world-streaming (server push), or grpc-hello-world-bidi-streaming (bi-directional streaming).

Learn More

To learn more about Kotlin protos check out these docs:

Let us know how it goes and if you have any Kotlin proto issues by filing them within the official protobuf project.

Additional thanks to Adam Cozzette, Brent Shaffer, David Jones, David Winer, Jeff Grimes, John Pampuch, and Kevin Bierhoff for their contributions to this release!