Tag Archives: Kotlin

Accelerated Kotlin build times with Kotlin Symbol Processing 1.0

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

Accelerated Kotlin build times with Kotlin Symbol Processing 1.0 image

Kotlin Symbol Processing (KSP), our new tool for building lightweight compiler plugins in Kotlin, is now stable! KSP offers similar functionality to the Kotlin Annotation Processing Tool (KAPT), however it’s up to 2x faster, offers direct access to Kotlin language constructs, and offers support for multiplatform targets.

Over the past few months, KSP has gone through 32 releases with over 162 bugs reported from the community and fixed by our team. If you were waiting to adopt it, now is the time to check it out.

Why we built KSP

On the Android team, we regularly ask developers: what are your biggest frustrations with writing apps today? One of the top issues that comes up repeatedly is build speed. Over the years we’ve been making steady improvements to the Android build toolchain, and today we’re excited to add to those improvements with KSP. KSP is the next generation of annotation processing in Kotlin: it will dramatically improve build speed for Kotlin developers, and unlike KAPT, it offers support for Kotlin/Native and Kotlin/JS.

Why is KSP faster?

The Kotlin Annotation Processing Tool (KAPT) works with Java’s annotation processing infrastructure to make most Java language annotation processors work in Kotlin out of the box. To do this, KAPT compiles Kotlin code into Java stubs that retain information that Java annotation processors care about. Creating these stubs is costly though, and means the compiler must resolve all the symbols in your program multiple times (once to generate stubs, and then again to do the actual compilation).

KSP moves away from the stub generation model by working as a Kotlin compiler plugin — it allows annotation processors to read and analyze source programs and resources directly in Kotlin instead of requiring you to depend on the Java annotation processing infrastructure. This both dramatically improves build speed (up to 2x faster for Room's Kotlin test app) and means that KSP can be used for non-Android and non-JVM environments like Kotlin/Native and Kotlin/JS.

How to get started

To start using KSP, download the KSP playground project from GitHub, which shows how to use KSP both as an annotation processor and as a consuming app/library:

  • Annotation processor: A toy test-processor library that implements the builder pattern as a KSP processor
  • Consuming library: A workload directory that shows how to use the builder processor in a real-world Kotlin project

If you’re an app developer, check out the list of supported libraries and the quickstart guide for moving a module over from KAPT to KSP.

Using Moshi or Room with KSP

If you’re using Moshi or Room in your project, you can already try out KSP by making a quick fix to your module’s build file. For example, to use the KSP version of Room in a Gradle module you can simply replace the KAPT plugin with KSP and swap out the KSP dependency:

apply plugin: 'com.google.devtools.ksp'

dependencies {
  ...
  implementation "androidx.room:room-runtime:$room_version"
  kapt "androidx.room:room-compiler:$room_version"
  ksp "androidx.room:room-compiler:$room_version"

}

Check out the Room release notes for more info.

Conclusion

With the 1.0 release of KSP you will start to see improved build times for your Kotlin projects as you migrate away from libraries based on KAPT. We have also updated a number of Android specific libraries which are ready for you to try today and offer significant performance improvements.

Android @ Google I/O: 3 things to know in Modern Android Development

Posted by The Modern Android Development Team

This year’s Google I/O brought lots of updates for Modern Android Development. Here are the top 3 things you should know:

#1: Lots of new Jetpack library releases!

In recent months, several Jetpack libraries reached stable, beta or were just launched in alpha. Here are some the highlights:

To find out more about what’s new, check out the What’s new in Jetpack, What’s new in Compose and for a deep dive into Macrobenchmark: Measuring Jank and Startup with Macrobenchmark.

#2: Inspectors in Android Studio

Debugging your application becomes easier with all the inspectors provided by Android Studio Arctic Fox: for background work, like understanding what’s the status of your WorkManager workers, use Background Task Inspector; for UI use Layout Inspector, for both Android Views and Compose; for database debugging use Database Inspector.

To see the inspectors in action, check out What’s new in Android development tools.

#3: New features in Kotlin

We keep improving Kotlin on Android at all levels, from tools to APIs, and giving you different ways to learn. Kotlin Symbol Processing (KSP), now in alpha, provides a simplified compiler plugin API that can run up to 2 times faster than KAPT. Together with JetBrains, we’re addressing performance issues in the IDE and we’re seeing up to 20x faster auto-import suggestions. We added StateFlow support to DataBinding and new APIs for observing Flows in the UI without DataBinding. To learn about all the improvements we’ve made for Kotlin, check out the State of Kotlin on Android talk:

You can find all of this year’s Google I/O talks covering Modern Android Development in this playlist:

A conversation with Hebe He, a developer from Guangzhou

Posted by Brian Shen, Program Manager, Google Developers

Google Developer Groups are one of the largest community networks of developers in the world. Every group has an organizer that helps curate events based on the interests of their local developer community.

As we continue to explore how different Google Developer Groups build their communities, we interviewed Hebe He, an organizer of Google Developer Group Guangzhou in China. Learn more about how she is building the developer scene in China, thinking up new events for her community, and more below.

Hebe He, an organizer of Google Developer Group Guangzhou in China.

Hebe He, an organizer of Google Developer Group Guangzhou in China.

Tell us about yourself.

I am Hebe from China and I'm a native of Guangzhou. I'm the organizer of GDG Guangzhou, as well as an ambassador for Women Techmakers (WTM). I work at one of China's new electric-vehicle brands, where I'm responsible for the intelligent business operation of the Internet of Vehicles. I'm relatively outgoing and active, so I really like to deal with different people, whether it's at work or in other activities.

How did you learn about Google Developer Groups?

In 2014, I participated in GDG Guangzhou DevFest for the first time by coincidence and met the founder of GDG Guangzhou. Afterward, I joined the founder's company and volunteered at many GDG programs. In 2017, I officially became an organizer after the existing organizers recognized my ability and desire to contribute more to the GDG Guangzhou community.

Tell us more about Guangzhou and the developer community there.

Our community members are talented, passionate, and amazing. I see all kinds of possibilities in them. They're always excited for every event we hold, keep a fanatical attitude toward Google's technological innovation, and are particularly interested in Android, Kotlin, and Flutter.

What are events like in your community?

We highly value feedback from event participants, who are interested in a wide range of topics. For this reason, we generally use 15% of every event to cover non-technical topics, such as entrepreneurship, business management, and careers. For more comprehensive activities, such as DevFest, we increase the amount of non-technical content to roughly 30%.

What is your Google Developer Group focused on right now?

We devote most of our energy to improving the quality of activities. We try to add more elements to the event to strengthen the interaction of participants in hopes of improving the feedback mechanism and gaining more valuable suggestions for future event optimization. We also try to improve the quality of guests and themes, and pay more attention to event details, such as event announcements, registration, and check-in.

What’s your favorite community memory from a Google Developer Group event?

The memory that touches me the most is the construction of WTM Guangzhou. From the first event with only 80 developers to the audience of more than 500 people in recent years, it represents the recognition of, and support for, our events. There are many people who come to participate every year; some are actively encouraging their friends to participate and others are even urging us to hold events. They feel honored to be invited to our events and their enthusiasm endured during the pandemic.

What's next for you and your Google Developer Group?

There's still lots of room to grow in our community. We hope that we can continue to develop a Google Developer Group that reflects the best of Guangzhou. We also hope to find better ways to accumulate the experience shared by speakers and the value of community users.

If you want to grow your career and coding knowledge with people like Hebe He, join a Google Developer Group near you.

What’s new for Android developers at Google I/O

Cross-posted on the Android Developers blog by Karen Ng, Director, Product Management & Jacob Lehrbaum, Director of Developer Relations, Android & Play

As Android developers, we are all driven by building experiences that delight people around the world. And with people depending on your apps more than ever, expectations are higher and your jobs as developers aren’t getting easier. Today, at Google I/O, we covered a few ways that we’re trying to help out, whether it be through Android 12 - one of the biggest design changes ever, Jetpack, Jetpack Compose, Android Studio, and Kotlin to help you build beautiful high quality apps. We’re also helping when it comes to extending your apps wherever your users go, like through wearables and larger-screened devices. You can watch the full Developer Keynote, but here are a few highlights:

Android 12: one of the biggest design updates ever.

The first Beta of Android 12 just started rolling out, and it’s packed with lots of cool stuff. From new user safety features like permissions for bluetooth and approximate location, enhancements to performance like expedited jobs and start up animations, to delightful experiences with more interactive widgets and stretch overscrolling, this release is one of the biggest design updates to Android ever. You can read more about what’s in Android 12 Beta 1 here, so you can start preparing your apps for the consumer release coming out later this year. Download the Beta and try it with your apps today!

Android 12 visual

Jetpack Compose: get ready for 1.0 in July!

For the last few years, we’ve been hard at work modernizing the Android development experience, listening to your feedback to keep the openness–a hallmark of Android, but becoming more opinionated about the right way to do things. You can see this throughout, from Android Studio, a performant IDE that can keep up with you, to Kotlin, a programming language that enables you to do more with less code, to Jetpack libraries that solve the hardest problems on mobile with backward compatibility.

The next step in this offering is Jetpack Compose - our modern UI toolkit to easily build beautiful apps for all Android devices. We announced Compose here at Google I/O two years ago and since then have been building it in the open, listening to your feedback to make sure we got it right. With the Compose Beta earlier this year, developers around the world have created some truly beautiful, innovative experiences in half the time, and the response to the #AndroidDevChallenge blew our socks off!

With the forthcoming update of Material You (which you can read more about here), we’ll be adding new Material components as well as further support for building for large screens, making it fast and easy to build a gorgeous UI. We’re pressure testing the final bits in Compose and will release 1.0 Stable in July—so get ready!

Android Studio Arctic Fox: Design, Devices, & Developer Productivity!

Android Studio Arctic Fox (2020.3.1) Beta, the latest release of the official powerful Android IDE, is out today to help you build quality apps easier and faster. We have delivered and updated the suite of tools to empower three major themes: accelerate your UI design, extend your app to new devices, and boost your developer productivity. With this latest release you can create modern UIs with Compose tooling, see test results across multiple devices, and optimize debugging databases and background tasks with the App Inspector. We’re also making your apps more accessible with the Accessibility Scanner and more performant with Memory Profiler. And for faster build speeds, we have the Android Gradle plugin 7.0, new DSL, and variant APIs. You can learn more about the Android Studio updates here.

Android Studio Arctic Fox

Kotlin: the most used language by professional Android devs

Kotlin is now the most used primary language by professional Android developers according to our recent surveys; in fact, over 1.2M apps in the Play Store use Kotlin, including 80% of the top 1000 apps. And here at Google, we love it too: 70+ Google apps like Drive, Home, Maps and Play use Kotlin. And with a brand-new native solution to annotation processing for Kotlin built from the ground up, Kotlin Symbol Processing is available today, a powerful and yet simple API for parsing Kotlin code directly, showing speeds up to 2x faster with libraries like Room.

Android Jetpack: write features, not boilerplate

With Android Jetpack, we built a suite of libraries to help reduce boilerplate code so you can focus on the code you care about. Over 84% of the top 10,000 apps are now using a Jetpack library. And today, we’re unpacking some new releases for Jetpack, including Jetpack Macrobenchmark (Alpha) to capture large interactions that affect your app startup and jank before your app is released, as well as a new Kotlin Coroutines API for persisting data more efficiently via Jetpack DataStore (Beta). You can read about all the updates in Android Jetpack here.

Now is the time: a big step for Wear

The best thing about modern Android development is that these tools have been purpose built to help make it easy for you to build for the next era of Android, which is all about enabling devices connected to your phone–TVs, cars, watches, tablets–to work better together.

Starting today, we take a huge step forward with wearables. First, we introduced a unified platform built jointly with Samsung, combining the best of Wear and Tizen. Second, we shared a new consumer experience with revamped Google apps. And third, a world-class health and fitness service from Fitbit is coming to the platform. As an Android developer, it means you’ll have more reach, and you’ll be able to use all of your existing skills, tools, and APIs that make your mobile apps great, to build for a single wearables platform used by people all over the world.

Whether it’s new Jetpack APIs for Wear tailored for small screens and designed to optimize battery life, to the Jetpack Tiles API, so you can create a custom Tile for all the devices in the Wear ecosystem, there are a number of new features to help you build on Wear. And with a new set of APIs for Health and Fitness, created in collaboration with Samsung, data collection from sensors and metrics computation is streamlined, consistent, and accurate–like heart rate to calories to daily distance–from one trusted source. All this comes together in new tooling, with the release of Android Studio Arctic Fox Beta, like easier pairing to test apps, and even a virtual heart rate sensor in the emulator. And when your app is ready, users will have a much easier time discovering the world of Wear apps on Google Play, with some big updates to discoverability. You can read more about all of the Wear updates here.

Tapping the momentum of larger screens, like tablets, Chrome OS and foldables

When it comes to larger screens -- tablets, foldables, and Chrome OS laptops-- there is huge momentum. People are increasingly relying on large screen devices to stay connected with family and friends, go to school, or work remotely. In fact, there are over 250 million active large screen Android devices. Last year, Chrome OS grew +92% year over year–5 times the rate of the PC market, making Chrome OS the fastest growing and the second-most popular desktop OS. To help you take advantage of this momentum, we’re giving you APIs and tools to make optimizing that experience easier: like having your content resize automatically to more space by using SlidingpaneLayout 1.2.0 and a new vertical navigation rail component, Max widths on components to avoid stretched UIs, as well as updates to the platform, Chrome OS, and Jetpack windowmanager, so apps work better by default. You can learn more here.

Google Duo's optimized experience for foldable devices

Google Duo's optimized experience for foldable devices

This is just a taste of some of the new ways we’re making it easier for you to build high quality Android apps. Later today, we’ll be releasing more than 20 technical sessions on Android and Play, covering a wide range of topics such as background tasks, privacy, and Machine Learning on Android, or the top 12 tips to get you ready for Android 12. If building for cars, TVs, and wearables is your thing, we got that covered, too. You can find all these sessions - and more - on the I/O website. Beyond the sessions and news, there’s a number of fun ways to virtually connect with Googlers and other developers at this year’s Google I/O. You can check out the Android dome in I/O Adventure, where you can see new blog posts, videos, codelabs, and more. Maybe even test out your Jetpack Compose skills or take a virtual tour of the cars inside our dome!

What’s new for Android developers at Google I/O

Posted by Karen Ng, Director, Product Management & Jacob Lehrbaum, Director of Developer Relations, Android & Play

As Android developers, we are all driven by building experiences that delight people around the world. And with people depending on your apps more than ever, expectations are higher and your jobs as developers aren’t getting easier. Today, at Google I/O, we covered a few ways that we’re trying to help out, whether it be through Android 12 - one of the biggest design changes ever, Jetpack, Jetpack Compose, Android Studio, and Kotlin to help you build beautiful high quality apps. We’re also helping when it comes to extending your apps wherever your users go, like through wearables and larger-screened devices. You can watch the full Developer Keynote, but here are a few highlights:

Android 12: one of the biggest design updates ever.

The first Beta of Android 12 just started rolling out, and it’s packed with lots of cool stuff. From new user safety features like permissions for bluetooth and approximate location, enhancements to performance like expedited jobs and start up animations, to delightful experiences with more interactive widgets and stretch overscrolling, this release is one of the biggest design updates to Android ever. You can read more about what’s in Android 12 Beta 1 here, so you can start preparing your apps for the consumer release coming out later this year. Download the Beta and try it with your apps today!

Android 12 visual

Jetpack Compose: get ready for 1.0 in July!

For the last few years, we’ve been hard at work modernizing the Android development experience, listening to your feedback to keep the openness–a hallmark of Android, but becoming more opinionated about the right way to do things. You can see this throughout, from Android Studio, a performant IDE that can keep up with you, to Kotlin, a programming language that enables you to do more with less code, to Jetpack libraries that solve the hardest problems on mobile with backward compatibility.

The next step in this offering is Jetpack Compose - our modern UI toolkit to easily build beautiful apps for all Android devices. We announced Compose here at Google I/O two years ago and since then have been building it in the open, listening to your feedback to make sure we got it right. With the Compose Beta earlier this year, developers around the world have created some truly beautiful, innovative experiences in half the time, and the response to the #AndroidDevChallenge blew our socks off!

With the forthcoming update of Material You (which you can read more about here), we’ll be adding new Material components as well as further support for building for large screens, making it fast and easy to build a gorgeous UI. We’re pressure testing the final bits in Compose and will release 1.0 Stable in July—so get ready!

Android Studio Arctic Fox: Design, Devices, & Developer Productivity!

Android Studio Arctic Fox (2020.3.1) Beta, the latest release of the official powerful Android IDE, is out today to help you build quality apps easier and faster. We have delivered and updated the suite of tools to empower three major themes: accelerate your UI design, extend your app to new devices, and boost your developer productivity. With this latest release you can create modern UIs with Compose tooling, see test results across multiple devices, and optimize debugging databases and background tasks with the App Inspector. We’re also making your apps more accessible with the Accessibility Scanner and more performant with Memory Profiler. And for faster build speeds, we have the Android Gradle plugin 7.0, new DSL, and variant APIs. You can learn more about the Android Studio updates here.

Android Studio Arctic Fox

Kotlin: the most used language by professional Android devs

Kotlin is now the most used primary language by professional Android developers according to our recent surveys; in fact, over 1.2M apps in the Play Store use Kotlin, including 80% of the top 1000 apps. And here at Google, we love it too: 70+ Google apps like Drive, Home, Maps and Play use Kotlin. And with a brand-new native solution to annotation processing for Kotlin built from the ground up, Kotlin Symbol Processing is available today, a powerful and yet simple API for parsing Kotlin code directly, showing speeds up to 2x faster with libraries like Room.

Android Jetpack: write features, not boilerplate

With Android Jetpack, we built a suite of libraries to help reduce boilerplate code so you can focus on the code you care about. Over 84% of the top 10,000 apps are now using a Jetpack library. And today, we’re unpacking some new releases for Jetpack, including Jetpack Macrobenchmark (Alpha) to capture large interactions that affect your app startup and jank before your app is released, as well as a new Kotlin Coroutines API for persisting data more efficiently via Jetpack DataStore (Beta). You can read about all the updates in Android Jetpack here.

Now is the time: a big step for Wear

The best thing about modern Android development is that these tools have been purpose built to help make it easy for you to build for the next era of Android, which is all about enabling devices connected to your phone–TVs, cars, watches, tablets–to work better together.

Starting today, we take a huge step forward with wearables. First, we introduced a unified platform built jointly with Samsung, combining the best of Wear and Tizen. Second, we shared a new consumer experience with revamped Google apps. And third, a world-class health and fitness service from Fitbit is coming to the platform. As an Android developer, it means you’ll have more reach, and you’ll be able to use all of your existing skills, tools, and APIs that make your mobile apps great, to build for a single wearables platform used by people all over the world.

Whether it’s new Jetpack APIs for Wear tailored for small screens and designed to optimize battery life, to the Jetpack Tiles API, so you can create a custom Tile for all the devices in the Wear ecosystem, there are a number of new features to help you build on Wear. And with a new set of APIs for Health and Fitness, created in collaboration with Samsung, data collection from sensors and metrics computation is streamlined, consistent, and accurate–like heart rate to calories to daily distance–from one trusted source. All this comes together in new tooling, with the release of Android Studio Arctic Fox Beta, like easier pairing to test apps, and even a virtual heart rate sensor in the emulator. And when your app is ready, users will have a much easier time discovering the world of Wear apps on Google Play, with some big updates to discoverability. You can read more about all of the Wear updates here.

Tapping the momentum of larger screens, like tablets, Chrome OS and foldables

When it comes to larger screens -- tablets, foldables, and Chrome OS laptops-- there is huge momentum. People are increasingly relying on large screen devices to stay connected with family and friends, go to school, or work remotely. In fact, there are over 250 million active large screen Android devices. Last year, Chrome OS grew +92% year over year–5 times the rate of the PC market, making Chrome OS the fastest growing and the second-most popular desktop OS. To help you take advantage of this momentum, we’re giving you APIs and tools to make optimizing that experience easier: like having your content resize automatically to more space by using SlidingpaneLayout 1.2.0 and a new vertical navigation rail component, Max widths on components to avoid stretched UIs, as well as updates to the platform, Chrome OS, and Jetpack windowmanager, so apps work better by default. You can learn more here.

Google Duo's optimized experience for foldable devices

Google Duo's optimized experience for foldable devices

This is just a taste of some of the new ways we’re making it easier for you to build high quality Android apps. Later today, we’ll be releasing more than 20 technical sessions on Android and Play, covering a wide range of topics such as background tasks, privacy, and Machine Learning on Android, or the top 12 tips to get you ready for Android 12. If building for cars, TVs, and wearables is your thing, we got that covered, too. You can find all these sessions - and more - on the I/O website. Beyond the sessions and news, there’s a number of fun ways to virtually connect with Googlers and other developers at this year’s Google I/O. You can check out the Android dome in I/O Adventure, where you can see new blog posts, videos, codelabs, and more. Maybe even test out your Jetpack Compose skills or take a virtual tour of the cars inside our dome!

New curriculum for educators to teach Android app development

Posted by Kat Kuan, Developer Advocate, Android

We strive to make Android development content accessible to all, so that anyone can become an Android developer. Over the years, millions of students at all different levels have consumed our learning content and worked through courses and codelabs to advance their skills. We continue to update and release new content as the ever-changing industry continues to evolve.

As demand for skilled Android developers increases in the job marketplace, there is an even greater need for educators to train the next generation of Android developers. That is why we created these resources to help support and empower educators.

New Android Development with Kotlin instructor-led curriculum

Today we’re announcing the launch of our new instructor-led curriculum for Android Development with Kotlin. This is for classroom learning (virtual or in-person) with an instructor delivering lectures on important Android concepts, and students receiving hands-on practice through codelabs. The official course materials are now available and can be freely modified by instructors to adapt to their students’ needs.

This is a major update to the curriculum we released in 2018. The updates account for the most recent changes in the Android platform, from the release of the Android Jetpack libraries to Android development becoming Kotlin-first. The Kotlin programming language helps developers become more productive with more concise syntax and improved code safety. Over 60% of professional Android developers already use Kotlin, and it’s Google’s recommended programming language for new developers building Android apps. While instructors do not need Android or Kotlin experience to teach the curriculum, prior programming experience is recommended.

We’ve partnered with universities and skilling partners in India such as Shivaji University, I. K. Gujral Punjab Technical University, Chandigarh University, Ganpat University, Telangana Academy for Skill and Knowledge (TASK), and Information and Communication Technology Academy of Kerala, who will be some of the first to offer this curriculum to their students in the Spring, with more universities to follow in the Fall and coming semesters. With the curriculum now available publicly, educators are welcome to start teaching Android development.

“As it’s mostly a hands-on course, students learn implementations which helps them in their placements in Mobile app companies.” -Dr. Kavita S. Oza, Shivaji University

Android Study Jams content now available for all developers

Outside a formal classroom, learning in a peer group has also been shown as an effective way to learn Android. That is why we’re also making the Android Study Jams program available to all developers today. Android Study Jams enables a group of people to come together and learn Android development through hands-on codelabs in an online curriculum. An instructor is not needed to deliver lectures, but it is recommended to have a facilitator to organize the group meetings. No programming experience is needed to get started. Over 38,000 students in Google Developer Student Clubs around the globe have already participated in this program.

“Introducing people to Kotlin and being by their side at this first step which could touch their lives created great happiness and excitement for us.” - Ceren Tunay and Serkan Alc, Developer Student Club Turkey

With many paths to learning, it is always interesting to see the different journeys of students who become Android developers, and exciting to see the resulting personal success, innovative apps, and entrepreneurial pursuits they have. The following video highlights two developers and how learning Android development has shaped their careers.

For more details on these new offerings, check out the Android Development Resources for Educators.

For independent learners, we also offer self-paced learning content, Udacity courses and Nanodegrees, YouTube videos, and more resources on developer.android.com. Keep us posted on how your learning journey goes!

MAD Skills Kotlin and Jetpack: wrap-up

Posted by Florina Muntenescu, Developer Relations Engineer

Kotlin and Jetpack image

We just wrapped up another series of MAD Skills videos and articles - this time on Kotlin and Jetpack. We covered different ways in which we made Android code more expressive and concise, safer, and easy to run asynchronous code with Kotlin.

Check out the episodes below to level up your Kotlin and Jetpack knowledge! Each episode covers a specific set of APIs, talking both about how to use the APIs but also showing how APIs work under the hood. All the episodes have accompanying blog posts and most of them link to either a sample or a codelab to make it easier to follow and dig deeper into the content. We also had a live Q&A featuring Jetpack and Kotlin engineers.

Episode 1 - Using KTX libraries

In this episode we looked at how you can make your Android and Jetpack coding easy, pleasant and Kotlin-idiomatic with Jetpack KTX extensions. Currently, more than 20 libraries have a KTX version. This episode covers some of the most important ones: core-ktx that provides idiomatic Kotlin functionality for APIs coming from the Android platform, plus a few Jetpack KTX libraries that allow us to have a better user experience when working with APIs like LiveData and ViewModel.

Check out the video or the article:

Episode 2 - Simplifying APIs with coroutines and Flow

Episode 2, covers how to simplify APIs using coroutines and Flow as well as how to build your own adapter using suspendCancellableCoroutine and callbackFlow APIs. To get hands-on with this topic, check out the Building a Kotlin extensions library codelab.

Watch the video or read the article:

Episode 3 - Using and testing Room Kotlin APIs

This episode opens the door to Room, peeking in to see how to create Room tables and databases in Kotlin and how to implement one-shot suspend operations like insert, and observable queries using Flow. When using coroutines and Flow, Room moves all the database operations onto the background thread for you. Check out the video or blog post to find out how to implement and test Room queries. For more hands-on work - check out the Room with a view codelab.

Episode 4 - Using WorkManager Kotlin APIs

Episode 4 makes your job easier with WorkManager, for scheduling asynchronous tasks for immediate or deferred execution that are expected to run even if the app is closed or the device restarts. In this episode we go over the basics of WorkManager and look a bit more in depth at the Kotlin APIs, like CoroutineWorker.

Find the video here and the article here, but nothing compares to practical experience so go through the WorkManager codelab.

Episode 5 - Community tip

Episode 5 is by Magda Miu - a Google Developer Expert on Android who shared her experience of leveraging foundational Kotlin APIs with CameraX. Check it out here:

Episode 6 - Live Q&A

In the final episode we launched into a live Q&A, hosted by Chet Haase, with guests Yigit Boyar - Architecture Components tech lead, David Winer - Kotlin product manager, and developer relations engineers Manuel Vivo and myself. We answered questions from you on YouTube, Twitter and elsewhere.

Announcing gRPC Kotlin 1.0 for Android and Cloud

Posted by Louis Wasserman, Software Engineer and James Ward, Developer Advocate

Kotlin is now the fourth "most loved" programming language with millions of developers using it for Android, server-side / cloud backends, and various other target runtimes. At Google, we've been building more of our apps and backends with Kotlin to take advantage of its expressiveness, safety, and excellent support for writing asynchronous code with coroutines.

Since everything in Google runs on top of gRPC, we needed an idiomatic way to do gRPC with Kotlin. Back in April 2020 we announced the open sourcing of gRPC Kotlin, something we'd originally built for ourselves. Since then we've seen over 30,000 downloads and usage in Android and Cloud. The community and our engineers have been working hard polishing docs, squashing bugs, and making improvements to the project; culminating in the shiny new 1.0 release! Dive right in with the gRPC Kotlin Quickstart!

For those new to gRPC & Kotlin let's do a quick runthrough of some of the awesomeness. gRPC builds on Protocol Buffers, aka "protos" (language agnostic & high performance data interchange) and adds the network protocol for efficiently communicating with protos. From a proto definition the servers, clients, and data transfer objects can all be generated. Here is a simple gRPC proto:

message HelloRequest {
string name = 1;
}

message HelloReply {
string message = 1;
}

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

In a Kotlin project you can then define the implementation of the Greeter's SayHello service with something like:

object : GreeterGrpcKt.GreeterCoroutineImplBase() {
override suspend fun sayHello(request: HelloRequest) =
HelloReply
.newBuilder()
.setMessage("hello, ${request.name}")
.build()
}

You'll notice that the function has `suspend` on it because it uses Kotlin's coroutines, a built-in way to handle async / reactive IO. Check out the server example project.

With gRPC the client "stubs" are generated making it easy to connect to gRPC services. For the protoc above, the client stub can be used in Kotlin with:

val stub = GreeterCoroutineStub(channel)
val request = HelloRequest.newBuilder().setName("world").build()
val response = stub.sayHello(request)
println("Received: ${response.message}")

In this example the `sayHello` method is also a `suspend` function utilizing Kotlin coroutines to make the reactive IO easier. Check out the client example project.

Kotlin also has an API for doing reactive IO on streams (as opposed to requests), called Flow. gRPC Kotlin generates client and server stubs using the Flow API for stream inputs and outputs. The proto can define a service with unary streaming or bidirectional streaming, like:

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

In this example, the server's `sayHello` can be implemented with Flows:

object : GreeterGrpcKt.GreeterCoroutineImplBase() {
override fun sayHello(requests: Flow<HelloRequest>): Flow<HelloReply> {
return requests.map { request ->
println(request)
HelloReply.newBuilder().setMessage("hello, ${request.name}").build()
}
}
}

This example just transforms each `HelloRequest` item on the flow to an item in the output / `HelloReply` Flow.

The bidirectional stream client is similar to the coroutine one but instead it passes a Flow to the `sayHello` stub method and then operates on the returned Flow:

val stub = GreeterCoroutineStub(channel)
val helloFlow = flow {
while(true) {
delay(1000)
emit(HelloRequest.newBuilder().setName("world").build())
}
}

stub.sayHello(helloFlow).collect { helloResponse ->
println(helloResponse.message)
}

In this example the client sends a `HelloRequest` to the server via Flow, once per second. When the client gets items on the output Flow, it just prints them. Check out the bidi-streaming example project.

As you've seen, creating data transfer objects and services around them is made elegant and easy with gRPC Kotlin. But there are a few other exciting things we can do with this...

Android Clients

Protobuf compilers can have a "lite" mode which generates smaller, higher performance classes which are more suitable for Android. Since gRPC Kotlin uses gRPC Java it inherits the benefits of gRPC Java's lite mode. The generated code works great on Android and there is a `grpc-kotlin-stub-lite` artifact which depends on the associated `grpc-protobuf-lite`. Using the generated Kotlin stub client is just like on the JVM. Check out the stub-android example and android example.

GraalVM Native Image Clients

The gRPC lite mode is also a great fit for GraalVM Native Image which turns JVM-based applications into ahead-of-time compiled native images, i.e. they run without a JVM. These applications can be smaller, use less memory, and start much faster so they are a good fit for auto-scaling and Command Line Interface environments. Check out the native-client example project which produces a nice & small 14MB executable client app (no JVM needed) and starts, connects to the server, makes a request, handles the response, and exits in under 1/100th of a second using only 18MB of memory.

Google Cloud Ready

Backend services created with gRPC Kotlin can easily be packaged for deployment in Kubernetes, Cloud Run, or really anywhere you can run docker containers or JVM apps. Cloud Run is a cloud service that runs docker containers and scales automatically based on demand so you only pay when your service is handling requests. If you'd like to give a gRPC Kotlin service a try on Cloud Run:

  1. Deploy the app with a few clicks
  2. In Cloud Shell, run the client to connect to your app on the cloud:
    export PROJECT_ID=PUT_YOUR_PROJECT_ID_HERE
    docker run -it gcr.io/$PROJECT_ID/grpc-hello-world-mvn \
    "java -cp target/classes:target/dependency/* io.grpc.examples.helloworld.HelloWorldClientKt YOUR_CLOUD_RUN_DOMAIN_NAME"

Here is a video of what that looks like:

Check out more Cloud Run gRPC Kotlin examples

Thank You!

We are super excited to have reached 1.0 for gRPC Kotlin and are incredibly grateful to everyone who filed bugs, sent pull requests, and gave the pre-releases a try! There is still more to do, so if you want to help or follow along, check out the project on GitHub.

Also huge shoutouts to Brent Shaffer, Patrice Chalin, David Winer, Ray Tsang, Tyson Henning, and Kevin Bierhoff for all their contributions to this release!

New language features and more in Kotlin 1.4

Posted by Wojtek Kaliciński, Developer Advocate, Android

When we adopted Kotlin as a supported language on Android, and then shifted to a Kotlin-first approach, one of the main drivers was the excitement and adoption from the developer community. As Kotlin has grown, we’ve seen continued investment in the language from JetBrains (Kotlin's creators), the open source community, and increasingly our own teams at Google.

Today we are excited to share the news about the Kotlin 1.4 release, the next milestone in the evolution of Kotlin, which contains new language features, improved compilers and tools. Below you'll find a brief rundown of some exciting new features in this release. You can read more about Kotlin 1.4 in the official announcement.

New language features

New language features introduced in Kotlin 1.4 improve the ergonomics of writing Kotlin code. Here's just one example:

SAM conversions for Kotlin interfaces

Previously, only functional interfaces (i.e. having just a Single Abstract Method - SAM) defined in the Java programming language benefited from the shorthand syntax in Kotlin:

executor.execute { println("This is shorthand for passing in a Runnable") }

In Kotlin 1.4 you can now mark your Kotlin interfaces as functional and get them to work in a similar manner by adding the fun keyword:

fun interface Transformer<T, U> {
   fun transform(x: T): U
}
val length = Transformer {
   x: String -> x.length
}

You can read more about new language features such as: mixing named and positional arguments, trailing comma, callable reference improvements, and using break and continue inside when included in loops on the Kotlin 1.4 release notes page.

Explicit API mode

One additional feature is the new Explicit API mode for authors of libraries written in Kotlin.

It enforces certain language properties of Kotlin that are normally optional, such as specifying visibility modifiers, as well as explicit typing for any public declarations, in order to prevent mistakes when designing the public API of your library. Refer to the linked documentation for instructions how to enable Explicit API mode and start using these additional checks.

Compiler improvements

The language features mentioned above are some of the most developer-facing changes in Kotlin 1.4, however the bulk of work went into improving the overall quality and performance of the Kotlin compiler.

One of the benefits all developers can take advantage of right now is the new, more powerful type inference algorithm, which is now enabled by default. It will help developers be more productive by supporting more smart-casts and cases where types can be inferred automatically.

Other than the type inference algorithm, Kotlin 1.4 also brings in optional, Alpha stability compiler backends for Kotlin/JVM and Kotlin/JS, which generate code in what's called internal representation (IR) also used in the Kotlin/Native backend.

The Kotlin/JVM IR backend is a requirement for Jetpack Compose, and Google engineers are working together with JetBrains to make it the default JVM compiler backend in the future.

That's why, even if you're not currently developing with Jetpack Compose, we encourage you to try out the new Kotlin/JVM backend, currently in alpha, and to file any issues and feature requests to the issue tracker.

To enable the new JVM IR backend, specify an additional compiler option in your Gradle build script:

kotlinOptions.useIR = true

Try Kotlin 1.4 now!

There are two steps to updating your projects and IDE to Kotlin 1.4.

First, make sure you are on the latest version of Android Studio to maximize the performance benefits and compatibility with the newest Kotlin plugin. Android Studio will prompt you when a Kotlin 1.4.0 plugin that is compatible with your IDE version is available. Alternatively, you can go to Preferences | Plugins and manually trigger the update.

Once the plugin is enabled, you can upgrade your app project to use Kotlin 1.4 by updating the Kotlin Gradle plugin version in your build.gradle scripts. Depending on how you manage your plugins, you either have to update the version in the top-level project's buildscript block:

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.0"
    }
}

Or change the version number in the plugins block in a module level build.gradle file:

plugins {
    id 'org.jetbrains.kotlin.android' version '1.4.0'
}

Make sure to read the language changes carefully and update your project's code to ensure compatibility with the latest release. Enjoy Kotlin 1.4!

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

11 Weeks of Android: Languages

Posted by David Winer, Product Manager

11 Weeks of Android, Week 5: Languages

This blog post is part of a weekly series for #11WeeksOfAndroid. Each week we’re diving into a key area of Android so you don’t miss anything. This week, we spotlighted languages; here’s a look at what you should know.

Modern Android development starts with outstanding language support. Together, Kotlin, the Java programming language, and C++ form the foundation for Android’s APIs and the tools you use every day for app development. This week we dove into all of the latest news across Android’s three core languages: from Kotlin coroutines to Android 11’s new Java APIs to better tools for native development, there’s a lot packed into the latest release.

Kotlin and coroutines

Kotlin is at the core of Android’s modern, opinionated APIs. We hear from Android developers around the world that they love Kotlin for how expressive it is, how it helps you write higher quality apps, and how easy it is to start using in your existing Java codebase. More than 70% of the top 1000 apps on the Play Store now use Kotlin, and SlashDataTM announced earlier this year that Kotlin has been the fastest growing language community in percentage terms over the past two years. With the Android 11 beta, we decided to further embrace Kotlin by officially recommending coroutines for asynchronous work on Android.

Coroutines make it easy to write, read, and understand async code. The coroutines library is stable and already has deep integration with many of the Jetpack libraries you may be using, including Room, LiveData, and WorkManager. If you’re new to coroutines, check out Android ❤️ Coroutines: How to Manage Async Tasks in Kotlin, the latest coroutines learning pathway, and our new coroutines developer guide.

Getting started with Kotlin

From Kotlin-first libraries in Android Jetpack to deep integration with the tools in Android Studio, Android is deeply committed to Kotlin — and there’s never been a better time to start using it. We’ve heard from many of you, though, that convincing your team to adopt Kotlin is not always easy. Even though Kotlin is 100% interoperable with the Java programming language, your teammates might have concerns. Is it worth spending the time learning a new language? How should you prioritize Kotlin against our other product and technology priorities?

This week we released a new case study from the Google Home team to help answer some of these questions. Over the course of one year, the Google Home team moved all new feature development to Kotlin and found their null pointer exceptions dropped by 33% during the same period. This is consistent with what we’ve heard from Android teams all over the world — from Duolingo to Zomato to Cash App — Kotlin is delivering value both in the form of productivity and higher app quality for teams large and small. For all our latest case studies and data on Kotlin, check out our new Kotlin case studies page.

For beginners, we announced the launch of our new Android Basics in Kotlin course. If you are just learning how to program, Android Basics teaches essential programming concepts like functions and variables and will take you from “Hello World” all the way up through building a whole collection of Android apps in Kotlin.

The Java programming language and C++

When we announced official support for Kotlin three years ago, we didn’t forget about the large number of Java and C++ Android developers. In the Android 11 release, we sought to keep improving our support for both of these languages. With the Android 11 beta, we upgraded our Java library support with a number of new APIs from OpenJDK 9, 10, and 11. We also unveiled Java library desugaring in Android Studio 4.0, making it easy to use many of these newer Java APIs even on older Android devices — for those of you who have asked for java.time support on older devices, we’ve heard you loud and clear, and it’s arrived. For all the latest information on how to make use of these newer APIs, check out Murat Yener’s talk Support for newer Java APIs. With Android 11, we also updated the Android runtime to make app startup even faster with I/O prefetching.

The C++ developer experience continues to get better, too. Android 11 included updates across the native toolchain, including better tools for profile-guided optimization (PGO) and improvements to native dependency management in Android Studio 4.0.

Ever-improving toolchains

Finally, we continue to focus on improvements to the D8 and R8 compilers in Android Studio. Android Studio comes with built-in support for the R8 shrinker, which helps you keep your app’s memory footprint small, leading to higher installs and retention among your users. We also recently added support for shrinking Kotlin libraries and apps that use Kotlin reflection with R8. For more information, check out Mads Ager and Morten Krogh-Jespersen’s latest Medium post.

Resources

You can find the entire playlist of #11WeeksOfAndroid video content here, and learn more about each week here. We’ll continue to spotlight new areas each week, so keep an eye out and follow us on Twitter and YouTube. Thanks so much for letting us be a part of this experience with you!