Tag Archives: Kotlin

Google Home reduces #1 cause of crashes by 33%

The Google Home app helps set up, manage, and control your Google Home, Google Nest, and Chromecast devices—plus thousands of connected home products like lights, cameras, thermostats, and more.

The engineering team behind the Google Home app benefits from using Kotlin and Android Jetpack libraries to boost engineering productivity and developer happiness.

What they did:

The Google Home team decided to incorporate Kotlin into their codebase to make programming more productive and to enable the usage of modern language features like var/val, smart casts, coroutines, and more. As of June 2020, about 30% of the code base is written in Kotlin, and Kotlin development is encouraged for all new features.

The team also adopted Jetpack libraries to improve developer velocity, decrease the need for boilerplate code maintenance, and reduce the necessary amount of code. Jetpack libraries also helped make their code more testable, since there are clearer functional boundaries and APIs.

Results:

"Efficacy and writing less code that does more is the ‘speed’ increase you can achieve with Kotlin.” - Jared Burrows, Software Engineer on Google Home

Switching to Kotlin resulted in a reduction in the amount of required code, compared to the equivalent of existing Java code. One example is the use of data classes and the Parcelize plugin: a class which was 126 hand-written lines in Java can now be represented in just 23 lines in Kotlin—an 80% reduction. Additionally, equality and parcelizing methods can be automatically generated and kept up to date. Many nested loops and filtering checks were also simplified using the functional methods available in Kotlin.

Because Kotlin can make nullability a part of the language, tricky situations can be avoided, like when inconsistent usage of nullability annotations in Java might lead to a missed bug. Since the team started migrating to developing new features with Kotlin, they saw a 33% decrease in NullPointerExceptions. Since this is the most common crash type on Google Play Console, reducing them led to a dramatically improved user experience.

With a large, mature app like Google Home—which has over a million lines of code—it’s helpful to be able to gradually add Jetpack libraries. Incorporating them allowed the team to consolidate and replace custom tailored solutions, sometimes even with a single library. Since Jetpack libraries can help engineers follow best practices and be less verbose (for example, using Room or ConstraintLayout), readability was increased as well. The team considers many of the newer Jetpack libraries ‘must-haves,’ including ViewModel and LiveData, both of which are used extensively in the Google Home codebase.

The Google Home app team found the Jetpack KTX integrations with Kotlin coroutines to be especially helpful. The team is now able to avoid tricky asynchronous programming bugs by associating coroutines with lifecycle-aware components like ViewModel.

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

Get Started:

Learn more about writing Android apps in Kotlin and using Android Jetpack libraries.

Learn Android and Kotlin with no programming experience

Posted by Kat Kuan, Developer Advocate, Android

Many people today are considering career paths that enable them to work remotely. App development allows for that style of work. For people who want a new opportunity, it’s possible to start learning Android today, even without prior programming experience.

In 2016, we released our Android Basics curriculum, which assumes no programming experience, and the response has been tremendous. Hundreds of thousands of students have been learning Android development and programming concepts simultaneously as they build apps. Since then, there have been big platform changes with four major releases of Android and support added for the Kotlin programming language. We also introduced Jetpack, a suite of libraries that make it easier to build better apps with less code. With all these new updates, it’s time to release the next generation of training content for beginners.

Today we’re announcing the launch of Android Basics in Kotlin, a new online course for people without programming experience to learn how to build Android apps. The course teaches Kotlin, a modern programming language that developers love because of its conciseness and how it increases productivity. Kotlin is quickly gaining momentum in industry. Over a single year from 2018 - 2019, Indeed Hiring Lab found a 76% increase in Kotlin jobs.*

Google announced that Android development is Kotlin-first, and 60% of professional Android developers have already adopted the language. In the Play Store, 70% of the top 1,000 apps use Kotlin. To keep pace and prepare for the future, there has never been a more opportune time to learn Android with Kotlin.

Learning to code for the first time can feel intimidating, but it is possible to learn without a technical background. From a recent Stack Overflow Developer Survey, nearly 40% of the professional developers who studied at university did not receive a formal computer science or software engineering degree.

To build your confidence, the Android Basics in Kotlin course offers step-by-step instructions on how to use Android Studio to build apps, as well as how to run them on an Android device (or virtual device). The goal is to expose you to the tools and resources that professional Android developers use. With hands-on practice, you learn the fundamentals of programming. By the end of the course, you will have completed a collection of Android apps to start building a portfolio.

Object detection & tracking gif Text recognition + Language ID + Translate gif

App screenshots from the course

This course is split up into units, where each unit is made up of a series of pathways. At the end of each pathway, there is a quiz to assess what you’ve learned so far. If you pass the quiz, you earn a badge that can be saved to your Google Developer Profile.
Object detection & tracking gif Text recognition + Language ID + Translate gif

Badges you can earn

The course is free for anyone to take. Basic computer literacy and basic math skills are recommended prerequisites. Unit 1 of the course is available today, with more units being released as they become available. If you’ve never built an app before but want to learn how, check out the Android Basics in Kotlin course.

If you already have programming experience, check out the other free training courses we offer in Kotlin:

We can’t wait to see what you build!

*from US tech job postings on Indeed.com

Sip a cup of Java 11 for your Cloud Functions

Posted by Guillaume Laforge, Developer Advocate for Google Cloud

With the beta of the new Java 11 runtime for Google Cloud Functions, Java developers can now write their functions using the Java programming language (a language often used in enterprises) in addition to Node.js, Go, or Python. Cloud Functions allow you to run bits of code locally or in the cloud, without provisioning or managing servers: Deploy your code, and let the platform handle scaling up and down for you. Just focus on your code: handle incoming HTTP requests or respond to some cloud events, like messages coming from Cloud Pub/Sub or new files uploaded in Cloud Storage buckets.

In this article, let’s focus on what functions look like, how you can write portable functions, how to run and debug them locally or deploy them in the cloud or on-premises, thanks to the Functions Framework, an open source library that runs your functions. But you will also learn about third-party frameworks that you might be familiar with, that also let you create functions using common programming paradigms.

The shape of your functions

There are two types of functions: HTTP functions, and background functions. HTTP functions respond to incoming HTTP requests, whereas background functions react to cloud-related events.

The Java Functions Framework provides an API that you can use to author your functions, as well as an invoker which can be called to run your functions locally on your machine, or anywhere with a Java 11 environment.

To get started with this API, you will need to add a dependency in your build files. If you use Maven, add the following dependency tag in pom.xml:

<dependency>
<groupId>com.google.cloud.functions</groupId>
<artifactId>functions-framework-api</artifactId>
<version>1.0.1</version>
<scope>provided</scope>
</dependency>

If you are using Gradle, add this dependency declaration in build.gradle:

compileOnly("com.google.cloud.functions:functions-framework-api")

Responding to HTTP requests

A Java function that receives an incoming HTTP request implements the HttpFunction interface:

import com.google.cloud.functions.*;
import java.io.*;

public class Example implements HttpFunction {
@Override
public void service(HttpRequest request, HttpResponse response)
throws IOException {
var writer = response.getWriter();
writer.write("Hello developers!");
}
}

The service() method provides an HttpRequest and an HttpResponse object. From the request, you can get information about the HTTP headers, the payload body, or the request parameters. It’s also possible to handle multipart requests. With the response, you can set a status code or headers, define a body payload and a content-type.

Responding to cloud events

Background functions respond to events coming from the cloud, like new Pub/Sub messages, Cloud Storage file updates, or new or updated data in Cloud Firestore. There are actually two ways to implement such functions, either by dealing with the JSON payloads representing those events, or by taking advantage of object marshalling thanks to the Gson library, which takes care of the parsing transparently for the developer.

With a RawBackgroundFunction, the responsibility is on you to handle the incoming cloud event JSON-encoded payload. You receive a JSON string, so you are free to parse it however you like, with your JSON parser of your choice:

import com.google.cloud.functions.Context;
import com.google.cloud.functions.RawBackgroundFunction;

public class RawFunction implements RawBackgroundFunction {
@Override
public void accept(String json, Context context) {
...
}
}

But you also have the option to write a BackgroundFunction which uses Gson for unmarshalling a JSON representation into a Java class (a POJO, Plain-Old-Java-Object) representing that payload. To that end, you have to provide the POJO as a generic argument:

import com.google.cloud.functions.Context;
import com.google.cloud.functions.BackgroundFunction;

public class PubSubFunction implements BackgroundFunction<PubSubMsg> {
@Override
public void accept(PubSubMsg msg, Context context) {
System.out.println("Received message ID: " + msg.messageId);
}
}

public class PubSubMsg {
String data;
Map<String, String> attributes;
String messageId;
String publishTime;
}

The Context parameter contains various metadata fields like timestamps, the type of events, and other attributes.

Which type of background function should you use? It depends on the control you need to have on the incoming payload, or if the Gson unmarshalling doesn’t fully fit your needs. But having the unmarshalling covered by the framework definitely streamlines the writing of your function.

Running your function locally

Coding is always great, but seeing your code actually running is even more rewarding. The Functions Framework comes with the API we used above, but also with an invoker tool that you can use to run functions locally. For improving developer productivity, having a direct and local feedback loop on your own computer makes it much more comfortable than deploying in the cloud for each change you make to your code.

With Maven

If you’re building your functions with Maven, you can install the Function Maven plugin in your pom.xml:

<plugin>
<groupId>com.google.cloud.functions</groupId>
<artifactId>function-maven-plugin</artifactId>
<version>0.9.2</version>
<configuration>
<functionTarget>com.example.Example</functionTarget>
</configuration>
</plugin>

On the command-line, you can then run:

$ mvn function:run

You can pass extra parameters like --target to define a different function to run (in case your project contains several functions), --port to specify the port to listen to, or --classpath to explicitly set the classpath needed by the function to run. These are the parameters of the underlying Invoker class. However, to set these parameters via the Maven plugin, you’ll have to pass properties with -Drun.functionTarget=com.example.Example and -Drun.port.

With Gradle

With Gradle, there is no dedicated plugin, but it’s easy to configure build.gradle to let you run functions.

First, define a dedicated configuration for the invoker:

configurations { 
invoker
}

In the dependencies, add the Invoker library:

dependencies {
invoker 'com.google.cloud.functions.invoker:java-function-invoker:1.0.0-beta1'
}

And then, create a new task to run the Invoker:

tasks.register("runFunction", JavaExec) {
main = 'com.google.cloud.functions.invoker.runner.Invoker'
classpath(configurations.invoker)
inputs.files(configurations.runtimeClasspath,
sourceSets.main.output)
args('--target',
project.findProperty('runFunction.target') ?:
'com.example.Example',
'--port',
project.findProperty('runFunction.port') ?: 8080
)
doFirst {
args('--classpath', files(configurations.runtimeClasspath,
sourceSets.main.output).asPath)
}
}

By default, the above launches the function com.example.Example on port 8080, but you can override those on the command-line, when running gradle or the gradle wrapper:

$ gradle runFunction -PrunFunction.target=com.example.HelloWorld \
-PrunFunction.port=8080

Running elsewhere, making your functions portable

What’s interesting about the Functions Framework is that you are not tied to the Cloud Functions platform for deploying your functions. As long as, in your target environment, you can run your functions with the Invoker class, you can run your functions on Cloud Run, on Google Kubernetes Engine, on Knative environments, on other clouds when you can run Java, or more generally on any servers on-premises. It makes your functions highly portable between environments. But let’s have a closer look at deployment now.

Deploying your functions

You can deploy functions with the Maven plugin as well, with various parameters to tweak for defining regions, memory size, etc. But here, we’ll focus on using the cloud SDK, with its gcloud command-line, to deploy our functions.

For example, to deploy an HTTP function, you would type:

$ gcloud functions deploy exampleFn \
--region europe-west1 \
--trigger-http \
--allow-unauthenticated \
--runtime java11 \
--entry-point com.example.Example \
--memory 512MB

For a background function that would be notified of new messages on a Pub/Sub topic, you would launch:

$ gcloud functions deploy exampleFn \
--region europe-west1 \
--trigger-topic msg-topic \
--runtime java11 \
--entry-point com.example.PubSubFunction \
--memory 512MB

Note that deployments come in two flavors as well, although the above commands are the same: functions are deployed from source with a pom.xml and built in Google Cloud, but when using a build tool other than Maven, you can also use the same command to deploy a pre-compiled JAR that contains your function implementation. Of course, you’ll have to create that JAR first.

What about other languages and frameworks?

So far, we looked at Java and the plain Functions Framework, but you can definitely use alternative JVM languages such as Apache Groovy, Kotlin, or Scala, and third-party frameworks that integrate with Cloud Functions like Micronaut and Spring Boot!

Pretty Groovy functions

Without covering all those combinations, let’s have a look at two examples. What would an HTTP function look like in Groovy?

The first step will be to add Apache Groovy as a dependency in your pom.xml:

<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>3.0.4</version>
<type>pom</type>
</dependency>

You will also need the GMaven compiler plugin to compile the Groovy code:

<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>1.9.0</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>

When writing the function code, just use Groovy instead of Java:

import com.google.cloud.functions.*

class HelloWorldFunction implements HttpFunction {
void service(HttpRequest request, HttpResponse response) {
response.writer.write "Hello Groovy World!"
}
}

The same explanations regarding running your function locally or deploying it still applies: the Java platform is pretty open to alternative languages too! And the Cloud Functions builder will happily build your Groovy code in the cloud, since Maven lets you compile this code thanks to the Groovy library.

Micronaut functions

Third-party frameworks also offer a dedicated Cloud Functions integration. Let’s have a look at Micronaut.

Micronaut is a “modern, JVM-based, full-stack framework for building modular, easily testable microservice and serverless applications”, as explained on its website. It supports the notion of serverless functions, web apps and microservices, and has a dedicated integration for Google Cloud Functions.

In addition to being a very efficient framework with super fast startup times (which is important, to avoid long cold starts on serverless services), what’s interesting about using Micronaut is that you can use Micronaut’s own programming model, including Dependency Injection, annotation-driven bean declaration, etc.

For HTTP functions, you can use the framework’s own @Controller / @Get annotations, instead of the Functions Framework’s own interfaces. So for example, a Micronaut HTTP function would look like:

import io.micronaut.http.annotation.*;

@Controller("/hello")
public class HelloController {

@Get(uri="/", produces="text/plain")
public String index() {
return "Example Response";
}
}

This is the standard way in Micronaut to define a Web microservice, but it transparently builds upon the Functions Framework to run this service as a Cloud Function. Furthermore, this programming model offered by Micronaut is portable across other environments, since Micronaut runs in many different contexts.

Last but not least, if you are using the Micronaut Launch project (hosted on Cloud Run) which allows you to scaffold new projects easily (from the command-line or from a nice UI), you can opt for adding the google-cloud-function support module, and even choose your favorite language, build tool, or testing framework:

Micronaut Launch

Be sure to check out the documentation for the Micronaut Cloud Functions support, and Spring Cloud Function support.

What’s next?

Now it’s your turn to try Cloud Functions for Java 11 today, with your favorite JVM language or third-party frameworks. Read the getting started guide, and try this for free with Google Cloud Platform free trial. Explore Cloud Functions’ features and use cases, take a look at the quickstarts, perhaps even contribute to the open source Functions Framework. And we’re looking forward to seeing what functions you’re going to build on this platform!

Handling Nullability in Android 11 and Beyond

Posted by David Winer, Kotlin Product Manager

Android blog banner

Last May at Google I/O, we announced that Android was going Kotlin first, and now over 60% of the top 1000 Android apps use Kotlin. One feature we love about Kotlin is that nullability is baked into its type system — when declaring a reference, you say upfront whether it can hold null values. In this post, we’ll look at how the Android 11 SDK does more to expose nullability information in its APIs and show how you can prepare your Kotlin code for it.

How does nullability in Kotlin work?

When writing code in Kotlin, you can use the question mark operator to indicate nullability:

KOTLIN

var x: Int = 1
x = null // compilation error

var y: Int? = 1
y = null // okay

This aspect of Kotlin makes your code safer — if you later call a method or try to access a property on a non-null variable like x, you know you’re not risking a null pointer exception. We hear over and over again that this feature of Kotlin gives developers more peace of mind and leads to higher quality apps for end users.

How does nullability work with the Java programming language?

Not all of your (or Android’s) APIs are written in Kotlin. Fortunately, the Kotlin compiler recognizes annotations on Java programming languages methods that indicate whether they produce nullable or non-nullable values. For example:

JAVA

public @Nullable String getCurrentName() {
   return currentName;
}

The @Nullable annotation ensures that when using the result of getCurrentName in a Kotlin file, you can’t dereference it without a null check. If you try, Android Studio will notify you of an error, and the Kotlin compiler will throw an error in your build. The opposite is true of @NonNull — it tells the Kotlin compiler to treat the method result as a non-null type, forbidding you from assigning that result to null later in your program.

The Kotlin compiler also recognizes two similar annotations, @RecentlyNullable and @RecentlyNonNull, which are the exact same as @Nullable and @NonNull, only they generate warnings instead of errors1.

Nullability in Android 11

Last month, we released the Android 11 Developer Preview, which allows you to test out the new Android 11 SDK. We upgraded a number of annotations in the SDK from @RecentlyNullable and @RecentlyNonNull to @Nullable and @NonNull (warnings to errors) and continued to annotate the SDK with more @RecentlyNullable and @RecentlyNonNull annotations on methods that didn’t have nullability information before.

What’s next

If you are writing in Kotlin, when upgrading from the Android 10 to the Android 11 SDK, you may notice that there are some new compiler warnings and that previous warnings may have been upgraded to errors. This is intended and a feature of the Kotlin compiler — these warnings tell you that you may be writing code that crashes your app at runtime (a risk you would miss entirely if you weren’t writing in Kotlin). As you encounter these warnings and errors, you can handle them by adding null checks to your code.

As we continue to make headway annotating the Android SDK, we’ll follow this same pattern — @RecentlyNullable and @RecentlyNonNull for one numbered release (e.g., Android 10), and then upgrade to @Nullable and @NonNull in the next release (e.g., Android 11). This practice will give you at least a full release cycle to update your Kotlin code and ensure you’re writing high-quality, robust code.

1. Due to rules regarding handling of annotations in Kotlin, there is currently a small set of cases where the compiler will throw an error for @Nullable references but not for @RecentlyNullable references.

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

Kotlin/Everywhere – it’s a wrap!

Posted by Florina Muntenescu, Developer Advocate (@FMuntenescu)

At Google I/O 2019 we announced that Android development will become increasingly Kotlin-first. Together with JetBrains, we also launched Kotlin/Everywhere - a global series of community led events focusing on the potential of using Kotlin everywhere; on Android, servers, web front-end and other platforms.

Kotlin/Everywhere events took place from May through December and we want to thank everyone for getting involved

?‍??‍?30,000+ developers participated in-person at Kotlin/Everywhere events

??200,000 views of live-streams and event recordings like Kotlin/Everywhere Bengaluru, Minsk, Chicago, Buenos Aires and more.

? 500+ events: from short evening meetups, half-day sessions, and full day events, to Kotlin/Everywhere tracks at larger events like DevFests, or even StudyJams that spanned several weeks.

?~30 speakers from Google and JetBrains gave ~70 talks at events around the world.

? 85+ countries: from United States to Chile, Kenya, Greece, Taiwan, New Zealand and so many more, with some countries hosting 1-2 events to some hosting dozens: Nigeria - 38, China - 27, India - 25 just to name a few.

? Many of the resources used or created for Kotlin/Everywhere by Google and JetBrains are available online:

General Kotlin:

Kotlin in Android:

Kotlin in Google Cloud Platform:

Multi-platform Kotlin:

We’re grateful for this engagement with Kotlin from communities around the world, as well as for all the organisers, speakers and attendees who made these events possible! To participate in more Kotlin events, check out JetBrains’ KotlinConf’19 Global initiative, happening through March 2020.

With all of the resources available, there’s never been a better time to adopt Kotlin… Everywhere!

Android’s commitment to Kotlin

Posted by David Winer, Kotlin Product Manager

Android and Kotlin banner

When we announced Kotlin as a supported language for Android, there was a tremendous amount of excitement among developers. Since then, there has been a steady increase in the number of developers using Kotlin. Today, we’re proud to say nearly 60% of the top 1,000 Android apps contain Kotlin code, with more and more Android developers introducing safer and more concise code using Kotlin.

During this year’s I/O, we announced that Android development will be Kotlin-first, and we’ve stood by that commitment. This is one of the reasons why Android is the gold partner for this year’s KotlinConf.

Seamless Kotlin on Android

In 2019, we focused on making programming in Kotlin on Android a seamless experience, with modern Kotlin-first APIs across the Android platform. Earlier this year, we launched a developer preview of Jetpack Compose, a modern UI toolkit for Android built using a Kotlin domain-specific language (DSL). We also incorporated coroutines into several of the flagship Jetpack libraries, including Room and Lifecycle. Finally, we brought Kotlin extensions (KTX) to even more major Google libraries, including Firebase and Play Core.

On the tooling side, we strengthened our commitment to Kotlin in Android Studio and the Android build pipeline. Significant updates to R8 (the code shrinker for Android) brought the ability to detect and handle Kotlin-specific bytecode patterns. Support was added for .kts Gradle build scripts in Android Studio, along with improved Kotlin support in Dagger. We worked closely with the JetBrains team to optimize support for the Kotlin plugin, and make the Kotlin editing experience in Android Studio fluid and fast.

Better Kotlin learning

This year we’ve also invested in quality Kotlin on Android learning content.

We released two free video learning courses in partnership with Udacity: Developing Android Apps in Kotlin and Advanced Android in Kotlin. This content was also released as the Codelab courses Android Kotlin Fundamentals and Advanced Android in Kotlin, for those who prefer text-based learning. The popular Kotlin Bootcamp for Programmers Udacity course was also published as a Codelabs course, helping provide a Kotlin foundation for non-Kotlin developers. Kotlin-based instructional Codelabs were also created for topics including Material Design, Kotlin coroutines, location, refactoring to Kotlin, billing in Kotlin, and Google Pay in Kotlin. It hasn’t been just about new content: we've updated Kotlin Codelab favorites to take advantage of important features such as coroutines.

Looking ahead

In 2020, Android development will continue to be Kotlin-first. We’ve been listening to your feedback, and will continue partnering with JetBrains to improve your experience with Kotlin.

This includes working with JetBrains to improve the Kotlin compiler over the next year. Our teams are making the compiler more extensible with a new backend, and making your builds faster with a significantly faster frontend. We’re also working with many of the largest annotation processors to make compilation faster for Kotlin code. You can also expect more Kotlin-first updates to Android, including more Jetpack libraries that make use of Kotlin features such as coroutines.

Thank you for letting us be part of your app development journey this year. We look forward to continuing the journey with you in 2020.

3 things to know about Kotlin from Android Dev Summit 2019

Last month’s #AndroidDevSummit was jam-packed with announcements and technical news...so much that we wouldn’t be surprised if you missed something. So all this month, we’ll be diving into key areas from throughout the summit so you don’t miss anything. First up, we’re spotlighting Kotlin, with the top things you should know:

#1: Kotlin momentum on Android

Kotlin is at the heart of modern Android development — and we’ve been excited to see how quickly it has won over developers around the world. At Android Dev Summit we announced that nearly 60% of the top 1000 Android apps on the Play Store now use Kotlin, and we’re seeing more developers adopt it every day. Kotlin has helpful features like null safety, data classes, coroutines, and complete interoperability with the Java programming language. We’re doubling down on Kotlin with more Kotlin-first APIs even beyond AndroidX — we just released KTX extensions, including coroutines support, for Play Core. There’s never been a better time to give Kotlin a try.

#2: Learn more: Getting started with Kotlin & diving into advanced Kotlin with coroutines

If you’re introducing Kotlin into an existing codebase, chances are that you’ll be calling the Java programming language from Kotlin and vice versa. At Android Dev Summit, developer advocates Murat Yener, Nicole Borrelli, and Wenbo Zhu took a look at how nullability, getters, setters, default parameters, exceptions, and more work across the two languages.

For those looking into more advanced Kotlin topics, we recommend watching Jose Alcérreca's and Yigit Boyar's talk that explains how coroutines and Flow can fit together with LiveData in your app's architecture and one on testing coroutines by Sean McQuillan and Manuel Vivo.

#3: Get certified in Kotlin

We announced the launch of our Associate Android Developer certification in Kotlin. Now you can prove your proficiency with modern Kotlin development on Android to your coworkers, your professional network, or even your future employer. As part of this launch, you can take this exam at a discount when using the code ADSCERT99 through January 25.

It’s especially great to hear from you, the Android community, at events like Android Dev Summit: what do you want to hear more about, and how can we help with something you’re working on. We asked you to submit your burning questions on Twitter and the livestream, and developer advocates Florina Muntenescu and Sean McQuillan answered your Kotlin and coroutines questions live during our #AskAndroid segment:

You can find the entire playlist of Android Dev Summit sessions and videos here. We’ll continue to spotlight other areas later this month, so keep an eye out and follow Android Developers on Twitter. Thanks so much for letting us be a part of this experience with you!

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

Kotlin named Breakout Project of the Year at OSCON

Posted by Wojtek Kaliciński, Developer Advocate, Android

Stephanie on Stage with Kotlin on screen

Stephanie Saad Cuthbertson announces support for Kotlin during the Developer Keynote at I/O 2017.

Today at OSCON (the O'Reilly Open Source Software Conference), Kotlin was awarded the Open Source Award for Breakout Project of the Year.

There is no doubt to us why Kotlin received this award: it’s a fast moving (but thoughtfully developed) programming language that lets you write better code, faster. It’s great to see Kotlin continue to receive the sort of recognition as Breakout Project of the Year, building on other awards like #1 fastest growing language on Github.

We’re big fans of Kotlin, and we’ve heard that you are too – feedback from you is in part why we announced support for the language over two years ago. This meant bundling the Kotlin plugin in Android Studio, along with promising to support Kotlin-built apps going forward.

But there was a long way to go for many teams at Google to provide a first class experience with Kotlin in the Android ecosystem, and to convince developers that Kotlin on Android is not just a fad, but is here to stay.

If you haven’t tried Kotlin yet, now is a great time to start! In fact, in the past two years, we’ve been adding a number of new features and upgrades to the Kotlin for Android experience, including:

  • Android Jetpack APIs now have first class support for Kotlin Coroutines, transforming the way we do async operations on Android. This includes Room, LiveData, ViewModels, WorkManager and more coming in the future.

  • Many Jetpack libraries have Kotlin extension libraries (KTX) to make using them even more fluent with Kotlin.
  • The compilation toolchain has received many improvements for Kotlin, including compiler enhancements, incremental annotation processing with KAPT, and Kotlin-specific R8 optimizations.
  • All of our documentation pages now contain Kotlin code snippets, so you can easily compare how our APIs work in both languages.
Kotlin code snippet
  • Most of our flagship samples are also written in Kotlin (including IOSched, Plaid, Sunflower and many more), along with any new samples that we make in the future.
  • We've added a language switcher to our API reference pages, so you can have a Kotlin view of the AndroidX library and the Android framework.
Kotlin view of the AndroidX library
  • We doubled down on providing guidance to developers and teams who want to switch to Kotlin on our developers.android.com/kotlin pages.
  • Our Developer Relations engineers are posting real life examples and guides on integrating Kotlin in your apps on our Medium publication, such as the great intro to Coroutines on Android series and many more.
  • If you prefer to learn Kotlin in person, you can join one of the many Kotlin/Everywhere events happening around the world. If you are an organizer in a local developer community, consider signing up to host your own event!
    This initiative is a cooperation between JetBrains and Google.
  • For those of you who don't have access to in-person training, we added a new, free course on Udacity for Developing Android apps in Kotlin. Our Kotlin Bootcamp for Programmers course is still available as well!
  • We have worked with many external partners to gather feedback and learn about their experiences with Kotlin, such as this case study with Square.
  • And lastly, we've enabled Kotlin as a supported language for Android app teams at Google. We're already seeing adoption in apps such as Google Home, Google Drive, Android System UI, Nest, with many more to follow.

The road to fully supporting Kotlin on Android was not always easy, but it was truly rewarding seeing Kotlin adoption among professional Android developers rise from a handful of early adopters to around 50% since the original announcement!

We were confident when we announced earlier this year at Google I/O 2019 that Android is going increasingly Kotlin-first, opening up the possibility for APIs built specifically around Kotlin and for Kotlin users, starting with the new, declarative UI toolkit - Jetpack Compose (still in early development).

We want to congratulate JetBrains, our partners through the Kotlin Foundation and creators of Kotlin, on receiving the OSCON Open Source Award today. It shows how disruptive and transformative Kotlin has been, and not just for the Android developer community, but beyond.

We know one thing: on Android, Kotlin is here to stay.

Truth 1.0: Fluent Assertions for Java and Android Tests

Software testing is important—and sometimes frustrating. The frustration can come from working on innately hard domains, like concurrency, but too often it comes from a thousand small cuts:
assertEquals("Message has been sent", getString(notification, EXTRA_BIG_TEXT));
assertTrue(
    getString(notification, EXTRA_TEXT)
        .contains("Kurt Kluever <[email protected]>"));
The two assertions above test almost the same thing, but they are structured differently. The difference in structure makes it hard to identify the difference in what's being tested.
A better way to structure these assertions is to use a fluent API:
assertThat(getString(notification, EXTRA_BIG_TEXT))
    .isEqualTo("Message has been sent");
assertThat(getString(notification, EXTRA_TEXT))
    .contains("Kurt Kluever <[email protected]>");
A fluent API naturally leads to other advantages:
  • IDE autocompletion can suggest assertions that fit the value under test, including rich operations like containsExactly(permission.SEND_SMS, permission.READ_SMS).
  • Failure messages can include the value under test and the expected result. Contrast this with the assertTrue call above, which lacks a failure message entirely.
Google's fluent assertion library for Java and Android is Truth. We're happy to announce that we've released Truth 1.0, which stabilizes our API after years of fine-tuning.



Truth started in 2011 as a Googler's personal open source project. Later, it was donated back to Google and cultivated by the Java Core Libraries team, the people who bring you Guava.
You might already be familiar with assertion libraries like Hamcrest and AssertJ, which provide similar features. We've designed Truth to have a simpler API and more readable failure messages. For example, here's a failure message from AssertJ:
java.lang.AssertionError:
Expecting:
  <[year: 2019
month: 7
day: 15
]>
to contain exactly in any order:
  <[year: 2019
month: 6
day: 30
]>
elements not found:
  <[year: 2019
month: 6
day: 30
]>
and elements not expected:
  <[year: 2019
month: 7
day: 15
]>
And here's the equivalent message from Truth:
value of:
    iterable.onlyElement()
expected:
    year: 2019
    month: 6
    day: 30

but was:
    year: 2019
    month: 7
    day: 15
For more details, read our comparison of the libraries, and try Truth for yourself.

Also, if you're developing for Android, try AndroidX Test. It includes Truth extensions that make assertions even easier to write and failure messages even clearer:
assertThat(notification).extras().string(EXTRA_BIG_TEXT)
    .isEqualTo("Message has been sent");
assertThat(notification).extras().string(EXTRA_TEXT)
    .contains("Kurt Kluever <[email protected]>");
Coming soon: Kotlin users of Truth can look forward to Kotlin-specific enhancements.
By Chris Povirk, Java Core Libraries

Kotlin Is Everywhere! Join the global event series

Posted by Posted by Florina Muntenescu & Wojtek Kaliciński, Developer Advocates, Android

Last week at Google I/O, we announced a big step: Android development will become increasingly Kotlin-first. It’s a language that many of you already love: over 50% of professional Android developers now use Kotlin, and it’s the fastest-growing language on GitHub. As part of this announcement, many new Jetpack APIs and features will be offered first in Kotlin. So if you’re starting a new project, you should try writing it in Kotlin; code written in Kotlin often means much less code for you–less code to type, test, and maintain.

To help you dive deeper into Kotlin, we’re happy to announce a new program we’re launching together with JetBrains: Kotlin/Everywhere, a series of community-driven events focussing on the potential of Kotlin on all platforms. We are aiming to help learn the essentials and best practices of using Kotlin everywhere, be it for Android, back-end, front-end and other platforms.

Join the Kotlin/Everywhere global event series between June and December 2019.

Who can attend the events?

Whether you are a developer, a speaker, a Kotlin User Group, a Google Developer Group member or any other community leader join us. Anyone interested in learning Kotlin and its ecosystem, sharing knowledge, and hosting a Kotlin-focused event is welcome to attend.

If you are a developer wanting to learn more about Kotlin, or a speaker excited to share your Kotlin experience with others, you can find events near you to join. Just go to the map on the website. More events will be added over time.

How to host your Kotlin/Everywhere event?

If you want to host an event in your city, you can begin by checking out the detailed organizers’ guide. It will help you to decide on the format and what kind of support you might need. All the necessary tips and tricks, materials, and branding assets are inside. Go ahead and submit your event on the official web page.

Besides the detailed organizers’ guide, we also provide you with resources such as content, codelabs, and guidance to help you maximize your success. You can also apply for support: we have speakers from Google/JetBrains and can help by providing funding for venue, food and drinks, swag, or other. We will also list your event on the official website.

Still have questions? Ask them at our hangout sessions for organizers on May 16 and 17.

Let us know if you want to take part! Apply at kotl.in/everywhere