Kotlin For Android: An Introduction
See how Kotlin For Android makes developing Android apps far more enjoyable. Learn how simple it is by creating your very own book searching app. By Matei Suica.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Kotlin For Android: An Introduction
25 mins
- Why Kotlin For Android?
- Getting Started
- Setting up Your Environment
- Working With Java and Kotlin Together
- Some Things Never Change
- How Cool is Kotlin?
- Declaring Variables
- Null Safety
- Nullable Types and Non-Null Types
- Late Initialization Variables
- Safe Calls
- The !! Operator
- The Elvis Operator
- Type Inference
- The Java to Kotlin Converter
- Kotlin is Evolving
- Coroutines
- Improvements to when expression
- More Numbers
- Code Style Support in the IDE
- Where To Go From Here?
The Elvis Operator
The Elvis Operator (?:) looks like the ternary conditional operator in Java but works differently. It also looks like Elvis Presley’s hair if you tilt your head 90 degrees to the left :] You can see an example of this when trying to get the length of the cover ID:
val len = coverId?.length ?: 0
If the expression to the left of the Elvis operator is not null
, it returns the result of the expression. Otherwise, it returns the expression to the right.
Similarly to an if-else
statement, Elvis only evaluates the expression on the right if the one on the left side is null
. The equivalent would be:
val len: Int
if(coverId?.length != null) {
len = coverId?.length
} else {
len = 0
}
It’s shorter with the Kotlin way, isn’t it?
Type Inference
Kotlin also supports type inference. This means the compiler can deduce variable types from the initializer. You can still declare the type if you want or if the compiler can’t infer it. For example, the types of the imageUrlBase
and imageURL
variables are inferred from their initializers.
private val imageUrlBase = "http://covers.openlibrary.org/b/id/"
private var imageURL = ""
The compiler tracks the inferred type of each variable, each as a String
. Any values assigned after that to the variable must also be of that String
type. For numbers, you need to make the type of variable clear to the compiler.
var longVar = 0L
var floatVar = 0.0f
var doubleVar = 0.0
var integerVar = 0
The Java to Kotlin Converter
I like to call this tool The Kotlinifier. Unfortunately, the JetBrain team isn’t trying to be funny. Still, the converter is the best tool ever made to ease the transition from one programming language to another.
Since Kotlin was made by developers for developers, they knew what language users would want. These tools are what the language developer team used to transition themselves from Java to Kotlin. That’s why the converter is so good!
Try it out. Take this sanity-saving feature for a test drive by converting the DetailActivity.java file to Kotlin.
Open the DetailActivity.java class and go to Code ▸ Convert Java File to Kotlin File or use the shortcut Command + Shift + Option + K:
You will get a notice like shown, click OK. This will replace the Java file with a Kotlin one. This notice however is only showed when necessary, so don’t always expect it.
That’s it. You’ve converted a Java class into a Kotlin class. :]
Compare the converted DetailActivity
with the DetailActivityKotlin
class. Pay attention to the choices the converter made. It doesn’t always make the best choices, but it does produce working code. Always review the converted code when you use this feature. You can even learn language features from the converter!
Now, reset MainActivity
to refer to the converted code:
Intent detailIntent = new Intent(this, DetailActivity.class);
Build and run and go to the detail screen, and you’ll see the converted code works as well as the code you had in DetailActivityKotlin
. :]
Kotlin is Evolving
While other programming languages have already reached maturity, Kotlin is still in its infancy. The latest version right now is 1.3, and it came with a lot of new features. Some of the features were already in the language as experimental features and some are all new. Some are also improvements to already existing constructs. Here are some highlights that you should know about.
Coroutines
Coroutines are a more advanced feature of Kotlin that allows developers to run asynchronous code. You might not know about coroutines now, but it’s worth mentioning that the feature is now stable. If you ever need to run a non-blocking piece of code, check out Coroutines.
Improvements to when
expression
Kotlin’s equivalent to Java’s switch
is when
. In Kotlin 1.3, the when
subject can be captured on the spot. You no longer need to assign a val
right before the block.
when (val response = executeRequest()) {
is Success -> response.body
is HttpError -> throw HttpException(response.status)
}
More Numbers
For some applications, it makes sense to use unsigned number types. Getting the sign out of the way makes room for new possibilities. Kotlin 1.3 brings back the old unsigned concept: UByte
, UShort
, UInt
and ULong
are all new and experimental. Use them carefully!
Code Style Support in the IDE
Remember Java Coding Conventions? Yeah, me neither. Kotlin has a pretty solid coding conventions document that all Kotlin developers should read, learn and follow religiously. That’s why now you can set up your IntelliJ-based IDE to format your code The Kotlin Way instead of its default. This will help you keep your code nice and respectful of the recommendations.
There are many more changes in Kotlin 1.3. To check them all out, go to the changelog. Once you’re more advanced in the art of Kotlin, you’ll be amazed at how useful these additions are.
Where To Go From Here?
Congratulations! You’ve learned a lot about Kotlin! You recoded a Java Activity in Kotlin and used the Kotlin plugin to convert a Java source file into a Kotlin source file. Find the final project and compare your results by clicking the Download Materials button at the top or bottom of this tutorial.
I suggest reading further on Null Safety in Kotlin in the documentation.
You can also use the Kotlin online compiler to try out code samples and improve your knowledge of the language.
You’ve only scratched the surface of Kotlin’s amazing possibilities. If you’re excited by what you’ve read here, check out other Kotlin topics. There’s a lot to learn about Data Classes, Extensions, Lambdas, or String Templates.
I hope you enjoyed this Kotlin for Android tutorial. If you have any questions or comments, join the forum discussion below!