Android Developer
Android Developer
In this course, you will build apps by writing code in the Kotlin programming
language, which is the language recommended by Google when creating new
Android apps.
To get started on building Android apps in Kotlin, it's important to first establish a
solid foundation of programming concepts in Kotlin. With the codelabs in this
pathway, you will learn about Kotlin programming basics before diving into app
creation.
2. Get started
In this codelab, you explore and modify simple programs in Kotlin. You can think of a program as a
series of instructions for a computer or mobile device to perform some action, such as display a
message to a user or calculate the cost of items in a shopping cart. The step-by-step instructions for
what the computer should do is called code. When you modify the code in a program, the output
can change.
You use a tool called a code editor to write and edit your code. It's similar to a text editor in which
you can write and edit text, but a code editor also provides functionality to help you write code
more accurately. For example, a code editor shows autocomplete suggestions while you type, and
displays error messages when code is incorrect.
To practice the basics of the Kotlin language, you will use an interactive code editor called the Kotlin
Playground. You can access it from a web browser, so you don't need to install any software on your
computer. You can edit and run Kotlin code directly in the Kotlin Playground and see the output.
Note that you can't build Android apps within the Kotlin Playground. In later pathways, you will
install and use a tool called Android Studio to write and edit your Android app code.
Now that you have some context on Kotlin, take a look at your first program!
fun main() {
println("Hello, world!")
}
Even if you've never programmed before, can you guess what the program does?
When you click the Run button, a lot happens. Code in the Kotlin programming
language is meant to be understood by humans, so that people can more easily
read, write, and collaborate on Kotlin programs. However, your computer doesn't
immediately understand this language.
You need something called the Kotlin compiler, which takes the Kotlin code you
wrote, looks at it line by line, and translates it into something that the computer can
understand. This process is called compiling your code.
If your code compiles successfully, your program will run (or execute). When the
computer executes your program, it performs each of your instructions. If you've
ever followed a cooking recipe, performing each step in the recipe is considered
executing each instruction.
Here's a screenshot of what you should see when you run your program.
When you click the Run button, a lot happens. Code in the Kotlin programming
language is meant to be understood by humans, so that people can more easily
read, write, and collaborate on Kotlin programs. However, your computer doesn't
immediately understand this language.
You need something called the Kotlin compiler, which takes the Kotlin code you
wrote, looks at it line by line, and translates it into something that the computer can
understand. This process is called compiling your code.
If your code compiles successfully, your program will run (or execute). When the
computer executes your program, it performs each of your instructions. If you've
ever followed a cooking recipe, performing each step in the recipe is considered
executing each instruction.
Here's a screenshot of what you should see when you run your program.
At the bottom of the code editor, you should see a pane that shows the output, or
result, of your program:
Hello, world!
Cool! The purpose of this program is to print or display a message that says Hello,
world!.
Warning: If you don't see this result, copy and paste the three lines of code from the
previous section into the Kotlin Playground and try again.
How does this work? A Kotlin program is required to have a main function, which is
the specific place in your code where the program starts running. The main function
is the entry point, or starting point, of the program.
Hello, world!
Cool! The purpose of this program is to print or display a message that says Hello,
world!.
Warning: If you don't see this result, copy and paste the three lines of code from the
previous section into the Kotlin Playground and try again.
How does this work? A Kotlin program is required to have a main function, which is
the specific place in your code where the program starts running. The main function
is the entry point, or starting point, of the program.
5. Parts of a function
A function is a segment of a program that performs a specific task. You can have many functions in your
program or only a single one.
In your code, you define a function first. That means you specify all the instructions needed to perform that
task.
Once the function is defined, then you can call that function, so the instructions within that function can be
performed or executed.
Here's an analogy. You write out step-by-step instructions on how to bake a chocolate cake. This set of
instructions can have a name: bakeChocolateCake. Every time you want to bake a cake, you can execute
the bakeChocolateCake instructions. If you want 3 cakes, you need to execute
the bakeChocolateCake instructions 3 times. The first step is defining the steps and giving it a name,
which is considered defining the function. Then you can refer to the steps anytime you want them to be
executed, which is considered calling the function.
Note: You may hear the alternate phrase "declare a function." The words declare and define can be used
interchangeably and have the same meaning. You may also hear the term "function definition" or "function
declaration", which refer to the exact code that defines a function. In other languages declare and define
have different meanings.
Define a function
The function can also require some inputs, or information that needs to be provided when the
function is called. The function uses these inputs to accomplish its purpose. Requiring inputs is
optional, and some functions do not require inputs.
The function also has a body which contains the instructions to perform the task.
To translate the above diagram into Kotlin code, use the following syntax, or format, for defining a
function. The order of these elements matters. The fun word must come first, followed by the function
name, followed by the inputs in parentheses, followed by curly braces around the function body.
Notice the key parts of a function within the main function example you saw in the Kotlin Playground:
There is one line of code in the function body, println("Hello, world!"), which is located between
the opening and closing curly braces of the function.
Each part of the function is explained in more detail below.
Function keyword
To indicate that you're about to define a function in Kotlin, use the special word fun (short for function) on
a new line. You must type fun exactly as shown in all lowercase letters. You can't use func, function, or
some alternative spelling because the Kotlin compiler won't recognize what you mean.
These special words are called keywords in Kotlin and are reserved for a specific purpose, such as creating
a new function in Kotlin.
Function name
Functions have names so they can be distinguished from each other, similar to how people have names to
identify themselves. The name of the function is found after the fun keyword.
Choose an appropriate name for your function based on the purpose of the function. The name is usually a
verb or verb phrase. It's recommended to avoid using a Kotlin keyword as a function name.
Function names should follow the camel case convention, where the first word of the function name is all
lower case. If there are multiple words in the name, there are no spaces between words, and all other words
should begin with a capital letter.
calculateTip
displayErrorMessage
takePhoto
Function inputs
Notice that the function name is always followed by parentheses. These parentheses are where you list
inputs for the function.
An input is a piece of data that a function needs to perform its purpose. When you define a function, you
can require that certain inputs be passed in when the function is called. If there are no inputs required for a
function, the parentheses are empty ().
The following diagram shows a function that is called addOne. The purpose of the function is to add 1 to
a given number. There is one input, which is the given number. Inside the function body, there is code that
adds 1 to the number passed into the function.
In this next example, there is a function called printFullName. There are two inputs required for the
function, one for the first name and one for the last name. The function body prints out the first name and
last name in the output, to display the person's full name.
This last example shows a function that doesn't require any inputs to be passed in when the function is
called. When you call the displayHello() function, a Hello message gets printed to the output.
Function body
The function body contains the instructions needed to achieve the purpose of the function. You can locate
the function body by looking for the lines of code enclosed within the opening and closing curly braces.
Simple program explained
Look back at the simple program that you saw earlier in the codelab.
The program contains one function: the main function. main is a special function name in Kotlin. When
you're writing your code in the Kotlin Playground, your code should be written inside the main() function
or called from the main() function.
There's only one line of code in the body of this main() function:
println("Hello, world!")
This line of code is a statement because it performs a specific action, which is to print the Hello,
world! text in the output pane. More specifically, the println() function is being called on this line of
code. println() is a function that's already defined in the Kotlin language. That means the team of
engineers who created the Kotlin language already wrote out the function declaration for
the println() function. The function requires one input, which is the message that should be printed.
When you call the println() function, place the message text within parentheses after the function name.
Be sure to use quotation marks around the text to display, such as "Hello, world!".
When the program is executed, the message that was passed into the println() function is printed to the
output:
Hello, world!
Try it
Now look back at the original code in the program. Can you modify the code in the Kotlin Playground so
that the output shows this message instead?
Hello, Android!
Back
fun main() {
println("Hello, Android!")
}
Hello, Android!
Now can you change your code so that the message gets printed twice? See the
desired output:
Hello, Android!
Hello, Android!
1. Copy the initial println() statement and paste the second statement below it
within the function body. Both println() statements must be contained within
the curly braces of the main function. Now you have two statements within
the function body.
fun main() {
println("Hello, Android!")
println("Hello, Android!")
}
2. Run the program.
3. When you run your program, the output should be:
Hello, Android!
Hello, Android!
You can see how changes to the code affects the output.
Like other programming style guides, the issues covered span not only
aesthetic issues of formatting, but other types of conventions or coding
standards as well. However, this document focuses primarily on the hard-
and-fast rules that we follow universally, and avoids giving advice that
isn’t clearly enforceable (whether by human or tool).
Source files
All source files must be encoded as UTF-8.
Naming
If a source file contains only a single top-level class, the file name should
reflect the case-sensitive name plus the .kt extension. Otherwise, if a
source file contains multiple top-level declarations, choose a name that
describes the contents of the file, apply PascalCase, and append
the .kt extension.
// MyClass.kt
class MyClass { }
// Bar.kt
class Bar { }
fun Runnable.toBar(): Bar = // …
// Map.kt
fun <T, O> Set<T>.map(func: (T) -> O): List<O> = // …
fun <T, O> List<T>.map(func: (T) -> O): List<O> = // …
Special Characters
Whitespace characters
Aside from the line terminator sequence, the ASCII horizontal space
character (0x20) is the only whitespace character that appears
anywhere in a source file. This implies that:
For any character that has a special escape sequence ( \b, \n, \r, \t, \', \", \\,
and \$), that sequence is used rather than the corresponding Unicode
(e.g., \u000a) escape.
Non-ASCII characters
Example Discussion
Copyright / License
/*
* Copyright 2017 Google, Inc.
*
* ...
*/
/**
* Copyright 2017 Google, Inc.
*
* ...
*/
File-level annotations
Annotations with the "file" use-site target are placed between any header
comment and the package declaration.
Package statement
The package statement is not subject to any column limit and is never
line-wrapped.
Import statements
Top-level declarations
A .kt file can declare one or more types, functions, properties, or type
aliases at the top-level.
Source files are usually read from top-to-bottom meaning that the order,
in general, should reflect that the declarations higher up will inform
understanding of those farther down. Different files may choose to order
their contents differently. Similarly, one file may contain 100 properties,
another 10 functions, and yet another a single class.
What is important is that each file uses some logical order, which its
maintainer could explain if asked. For example, new functions are not just
habitually added to the end of the file, as that would yield “chronological
by date added” ordering, which is not a logical ordering.
The order of members within a class follow the same rules as the top-level
declarations.
Formatting
Braces
Braces are not required for when branches and if expressions which have
no more than one else branch and which fit on a single line.
if (string.isEmpty()) return
val result =
if (string.isEmpty()) DEFAULT_VALUE else string
when (value) {
0 -> return
// …
}
Braces are otherwise required for any if, for, when branch, do,
and while statements and expressions, even when the body is empty or
contains only a single statement.
if (string.isEmpty())
return // WRONG!
if (string.isEmpty()) {
return // Okay
}
if (string.isEmpty()) {
return // Okay
} else {
doLotsOfProcessingOn(string, otherParametersHere)
}
Non-empty blocks
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for
nonempty blocks and block-like constructs:
return Runnable {
while (condition()) {
foo()
}
}
Empty blocks
try {
doSomething()
} catch (e: Exception) {} // WRONG!
try {
doSomething()
} catch (e: Exception) {
} // Okay
Expressions
Indentation
Line wrapping
Code has a column limit of 100 characters. Except as noted below, any
line that would exceed this limit must be line-wrapped, as explained
below.
Exceptions:
Lines where obeying the column limit is not possible (for example, a
long URL in KDoc)
package and import statements
Where to break
Functions
When a function signature does not fit on a single line, break each
parameter declaration onto its own line. Parameters defined in this format
should use a single indent (+4). The closing parenthesis ( )) and return
type are placed on their own line with no additional indent.
Expression functions
Properties
When a property initializer does not fit on a single line, break after the
equals sign (=) and use an indent.
private val defaultCharset: Charset? =
EncodingRegistry.getInstance().getDefaultCharsetForPropertiesFiles(file)
Properties declaring a get and/or set function should place each on their
own line with a normal indent (+4). Format them using the same rules as
functions.
Read-only properties can use a shorter syntax which fits on a single line.
val defaultExtension: String get() = "kt"
Whitespace
Vertical
Horizontal
Beyond where required by the language or other style rules, and apart
from literals, comments, and KDoc, a single ASCII space also appears in
the following places only:
Separating any reserved word, such as if, for, or catch from an open
parenthesis (() that follows it on that line.
// WRONG!
for(i in 0..1) {
}
// Okay
for (i in 0..1) {
}
// WRONG!
}else {
}
// Okay
} else {
}
// WRONG!
if (list.isEmpty()){
}
// Okay
if (list.isEmpty()) {
}
// WRONG!
val two = 1+1
// Okay
val two = 1 + 1
// Okay
ints.map { value -> value.toString() }
But not:
the two colons (::) of a member reference.
// WRONG!
val toString = Any :: toString
// Okay
val toString = Any::toString
// WRONG
it . toString()
// Okay
it.toString()
// WRONG
for (i in 1 .. 4) print(i)
// Okay
for (i in 1..4) print(i)
// WRONG!
class Foo: Runnable
// Okay
class Foo : Runnable
// WRONG
fun <T: Comparable> max(a: T, b: T)
// Okay
fun <T : Comparable> max(a: T, b: T)
// WRONG
fun <T> max(a: T, b: T) where T: Comparable<T>
// Okay
fun <T> max(a: T, b: T) where T : Comparable<T>
// WRONG!
val oneAndTwo = listOf(1,2)
// Okay
val oneAndTwo = listOf(1, 2)
// WRONG!
class Foo :Runnable
// Okay
class Foo : Runnable
// WRONG!
var debugging = false//disabled by default
// Okay
var debugging = false // disabled by default
Specific constructs
Enum classes
MAYBE {
override fun toString() = """¯\_(ツ)_/¯"""
}
}
Since enum classes are classes, all other rules for formatting classes
apply.
Annotations
@Retention(SOURCE)
@Target(FUNCTION, PROPERTY_SETTER, FIELD)
annotation class Global
@JvmField @Volatile
var disposable: Disposable? = null
@[...] syntax may only be used with an explicit use-site target, and only for
combining 2 or more annotations without arguments on a single line.
@field:[JvmStatic Volatile]
var disposable: Disposable? = null
When writing a library, retain the explicit type declaration when it is part
of the public API.
Naming
Identifiers use only ASCII letters and digits, and, in a small number of
cases noted below, underscores. Thus each valid identifier name is
matched by the regular expression \w+.
Package Names
// Okay
package com.example.deepspace
// WRONG!
package com.example.deepSpace
// WRONG!
package com.example.deep_space
Type names
Class names are written in PascalCase and are typically nouns or noun
phrases. For example, Character or ImmutableList. Interface names may
also be nouns or noun phrases (for example, List), but may sometimes be
adjectives or adjective phrases instead (for example Readable).
Test classes are named starting with the name of the class they are
testing, and ending with Test. For example, HashTest or HashIntegrationTest.
Function names
Function names are written in camelCase and are typically verbs or verb
phrases. For example, sendMessage or stop.
@Composable
fun NameTag(name: String) {
// …
}
Function names should not contain spaces because this is not supported
on every platform (notably, this is not fully supported in Android).
// WRONG!
fun `test every possible case`() {}
// OK
fun testEveryPossibleCase() {}
Constant names
Constants are val properties with no custom get function, whose contents
are deeply immutable, and whose functions have no detectable side-
effects. This includes immutable types and immutable collections of
immutable types as well as scalars and string if marked as const. If any of
an instance’s observable state can change, it is not a constant. Merely
intending to never mutate the object is not enough.
Constants which are scalar values must use the const modifier.
Non-constant names
Backing properties
When a backing property is needed, its name should exactly match that of
the real property except prefixed with an underscore.
Camel case
1. Convert the phrase to plain ASCII and remove any apostrophes. For
example, “Müller’s algorithm” might become “Muellers algorithm”.
2. Divide this result into words, splitting on spaces and any remaining
punctuation (typically hyphens). Recommended: if any word already
has a conventional camel-case appearance in common usage, split
this into its constituent parts (e.g., “AdWords” becomes “ad
words”). Note that a word such as “iOS” is not really in camel case
per se; it defies any convention, so this recommendation does not
apply.
3. Now lowercase everything (including acronyms), then do one of the
following:
Uppercase the first character of each word to yield pascal
case.
Uppercase the first character of each word except the first to
yield camel case.
4. Finally, join all the words into a single identifier.
Note that the casing of the original words is almost entirely disregarded.
/**
* Multiple lines of KDoc text are written here,
* wrapped normally…
*/
fun method(arg: String) {
// …
}
Paragraphs
One blank line—that is, a line containing only the aligned leading asterisk
(*)—appears between paragraphs, and before the group of block tags if
present.
Block tags
Any of the standard “block tags” that are used appear in the
order @constructor, @receiver, @param, @property, @return, @throws, @see,
and these never appear with an empty description. When a block tag
doesn’t fit on a single line, continuation lines are indented 4 spaces from
the position of the @.
Summary fragment
Each KDoc block begins with a brief summary fragment. This fragment is
very important: it is the only part of the text that appears in certain
contexts such as class and method indexes.
Usage
KDoc is optional for “simple, obvious” functions like getFoo and properties
like foo, in cases where there really and truly is nothing else worthwhile to
say but “Returns the foo”.
Exception: overrides
A normal part of the coding process involves making mistakes and accidentally
writing invalid code. As a beginner, it may be confusing or overwhelming to
encounter these mistakes. But don't worry, this is expected. Code rarely works
perfectly the first time that it's written. Just like how writing a document takes many
drafts, writing code can take many iterations until it works as expected.
If the code can't compile successfully, there's an error. For example, if you have a
typo, such as a missing quotation mark or parenthesis, the compiler won't
understand your code and can't translate it into steps for the computer to perform. If
your code doesn't work as expected, or you see an error message in your code
editor, you have to go back to your code and fix it. The process of solving these
errors is called troubleshooting.
1. Copy and paste the following code snippet into the Kotlin Playground and run
the program. What do you see?
fun main() {
println("Today is sunny!)
}
Ideally, you want to see the message Today is sunny! displayed. Instead, in the output
pane, you see exclamation point icons with error messages.
The error messages start with the word "Expecting" because the Kotlin compiler is
"expecting" something but not finding it in the code. In this case, the compiler is
expecting a closing quotation mark and a closing parenthesis for the code on the
second line of your program.
In the println() statement, notice that the message to display has an opening
quotation mark, but no closing quotation mark. Even though there is a closing
parenthesis in the code, the compiler thinks the parenthesis is part of the text to
print because there is no closing quotation mark before it.
2. Add the closing quotation mark after the exclamation point, before the closing
parenthesis.
fun main() {
println("Today is sunny!")
}
The main function contains one line of code, which is a println() statement, where the
text is enclosed in quotation marks and placed within the parentheses: "Today is
sunny!".
There shouldn't be any errors and the output pane should display this text:
Today is sunny!
Good work on fixing the error! Once you gain more experience in writing code and
troubleshooting errors, you'll realize how important it is to pay attention to
capitalization, spelling, spacing, symbols, and names when you're typing your code.
In the next section, you work on a series of exercises to practice what you've
learned. Solutions are provided at the end of the codelab, but try your best to find
the answer on your own first.
9. Exercises
1. Can you read the code in this program and guess what the output is (without running it in Kotlin
Playground)?
fun main() {
println("1")
println("2")
println("3")
}
Once you have a guess, copy and paste this code into the Kotlin Playground to check your answer.
2. Use the Kotlin Playground to create a program that outputs the following messages:
I'm
learning
Kotlin!
Monday
Tuesday
Wednesday
Thursday
Friday
For some early practice on troubleshooting, fix the errors in the following exercises. For each exercise,
copy the code into the Kotlin Playground in your browser. Try to run the program and you'll see an error
message appear.
4. Fix the error in this program, so that it produces the desired output.
fun main() {
println("Tomorrow is rainy")
Desired output:
Tomorrow is rainy
5. Fix the error in this program, so that it produces the desired output.
fun main() {
printLine("There is a chance of snow")
}
Desired output:
6. Fix the error in this program, so that it produces the desired output.
fun main() {
println("Cloudy") println("Partly Cloudy") println("Windy")
}
Desired output:
Cloudy
Partly Cloudy
Windy
7. Fix the error in this program, so that it produces the desired output.
fun main() (
println("How's the weather today?")
)
Desired output:
After you complete these exercises, check your answers against the solutions in the next section.
Back
10. Solutions
1. The output of the program is:
1
2
3
4. The closing curly brace that indicates the end of the function body for the main function is
missing on the third line of the program.
Correct code:
11. Conclusion
Great job on completing this introduction to Kotlin!
You worked with simple programs in Kotlin and ran them to see text printed to the
output. You modified the programs in different ways and observed how those
changes affected the output. It's normal to make mistakes when programming, so
you also began to learn about how to troubleshoot and correct errors in your code,
which is an important skill that will help you in the future.
Move on to the next codelab to learn how to use variables in Kotlin so that you can
create more interesting programs!
Summary
A Kotlin program requires a main function as the entry point of the program.
To define a function in Kotlin, use the fun keyword, followed by the name of
the function, any inputs enclosed in parentheses, followed by the function
body enclosed in curly braces.
The name of a function should follow camel case convention and start with a
lowercase letter.
Use the println() function call to print some text to the output.
Refer to the Kotlin style guide for formatting and code conventions to follow
when coding in Kotlin.
Troubleshooting is the process of resolving errors in your code.
Learn more
Hello World
Program entry point
Print to the standard output
Basic syntax of functions
Keywords and operators
Functions Concept
println()
Kotlin style guide
fun main() {
println("Tomorrow is rainy")
}
Output:
Tomorrow is rainy
5. When you run the program, you see an Unresolved reference: printLine error. This is
because printLine() isn't a recognized function in Kotlin. You can also see the part of the code
causing the error highlighted in red in the Kotlin Playground. Change the function name
to println to print a line of text to the output, which fixes the error.
Correct code:
fun main() {
println("There is a chance of snow")
}
Output:
There is a chance of snow
6. When you run the program, you see an Unresolved reference: println error. This message
doesn't directly say how to fix the problem. This can sometimes happen when you troubleshoot an
error, and it requires you to take a deeper look at the code to resolve the unexpected behavior.
Upon closer look, the second println() function call in the code is red, which signals that's where the
problem is. Kotlin expects just one statement on each line. In this case, you can move the second and
third println() function calls onto separate new lines to solve the issue.
Correct code:
fun main() {
println("Cloudy")
println("Partly Cloudy")
println("Windy")
}
Output:
Cloudy
Partly Cloudy
Windy
7. If you run the program, you see the error: Function 'main' must have a body. A function body
should be enclosed within an opening curly brace and a closing curly brace { }, not opening and
closing parentheses ( ).
Correct code:
fun main() {
println("How's the weather today?")
}
Output:
Why store the value in a box and reference the box by its name when you can simply use the value
directly? The problem is that when your code uses values directly in all the instructions, your program will
only work for that specific case.
Here's an analogy that can make it easier to understand why variables are useful. Below is a letter for
someone you recently met.
Dear Lauren,
It was great meeting you today at the office. I look forward to seeing you on Friday.
This letter is great, but it only works for your specific situation with Lauren. What if you find yourself
writing the same letter many times but with slight variations for different people? It would be more
efficient to create a single letter template, leaving blanks for the parts that can change.
Dear ____ ,
It was great meeting you today at _____. I look forward to seeing you on ____ .
You can also specify the type of information that goes in each blank space. This ensures that the letter
template will be used as you expected.
Dear { name } ,
It was great meeting you today at { location } . I look forward to seeing you on { date } .
Conceptually, building an app is similar. You have placeholders for some data, while other parts of the app
stay the same.
In the above illustration of a news app, the "Welcome" text, the "Latest news for you" heading, and the
"View more articles" button text always stay the same. Conversely, the name of the user and the contents
of each article will change, so that would be a great opportunity to use variables to hold each piece of
information.
You don't want to write the code (or instructions) in your news app to only work for a user named Alex, or
for a news article that always has the same title and publication date. Instead, you want a more flexible
app, so you should write your code by referencing variable names
like name, article1Name, article1Date, and so on. Then your code becomes general enough to work
for many different use cases where the user's name could be different and the article details could be
different.
Change the data that's stored in these variables and you have a maps app that's flexible enough to display
the details of other locations too.
Data types
When you decide what aspects of your app can be variable, it's important to specify what type of data can
be stored in those variables. In Kotlin, there are some common basic data types. The table below shows a
different data type in each row. For each data type, there's a description of what kind of data it can hold
and example values.
Float Decimal number (that is less precise than a Double). Has an f or F at the end of the 5.0f
number. -1630.209f
1.2940278F
Boolean true or false. Use this data type when there are only two possible values. Note true
that true and false are keywords in Kotlin. false
Note: For the valid ranges for the numerical data types (Int, Double, and Float), see Numbers. For
specifics on the difference between Double and Float, look at this table comparing the two data types.
Now that you are aware of some common Kotlin data types, which data type would be appropriate for each
of the variables identified in the location detail page you saw earlier?
Name of the location is text, so it can be stored in a variable whose data type is String.
Star rating of the location is a decimal number (such as 4.2 stars), so it can be stored as
a Double.
Whether the user saved this location only has two possible values (saved or not saved), so it's
stored as a Boolean, where true and false can represent each of those states.
Practice on two more scenarios below. Identify the use of variables and their data types in the following
apps.
1. In an app for watching videos, such as the YouTube app, there's a video details screen. Where are
variables likely used? What's the data type of those variables?
There isn't a single correct answer, but in a video-watching app, variables can be used for the following
pieces of data:
2. In an email app like Gmail, the inbox screen lists the most recent email messages received. Where
are variables likely used? What's the data type of those variables?
Again, there isn't a single correct answer. In an email app, variables can be used for the following pieces of
data:
Try it
1. Open your favorite app on your phone.
2. Identify where you think variables are used in the app on that particular screen.
4. Share your answers on social media with a screenshot of the app, an explanation of where you
think variables are used, and the hashtag #AndroidBasics.
Great work in this codelab so far! Move onto the next section to learn more about how variables and data
types are used in your code.
Back
Next
bug_report Report a mistake
Except as otherwise noted, the content of this page is licensed under the Creative Commons
Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For
details, see the Google Developers Site Polic
4. Update variables
When an app is running, the value of a variable may need to be updated. For example, in a shopping app,
as the user adds items to the shopping cart, the cart total increases.
Let's simplify the shopping use case into a simple program. The logic is written out below with human
language, not in Kotlin. This is called pseudocode because it describes the key points of how the code will
be written, but it doesn't contain all the details of the code.
Note: Pseudocode is not meant to be working code that can be compiled, that's why it's called pseudo
code.
Update the cartTotal variable to 20, which is the current cost of the items in their shopping cart.
Print the total cost of the items in their cart, which is the cartTotal variable, to the output.
To further simplify the code, you don't need to write the code for when the user adds items to the shopping
cart. (You haven't learned about how a program can respond to user input yet. That will come in a later
unit.) Hence, focus on the parts where you create, update, and print out the cartTotal variable.
1. Replace the existing code in the Kotlin Playground with the below program. In line 2 of the
program, you initialize the cartTotal variable to the value 0. Since you provide an initial value,
there's no need to specify the Int data type due to type inference. In line 3 of the program, you
attempt to update the cartTotal variable to 20 with the assignment operator (=). In line 4 of the
program, you print out the cartTotal variable using a string template.
fun main() {
val cartTotal = 0
cartTotal = 20
println("Total: $cartTotal")
}
3. Notice the error says that the val can't be reassigned. The error is on the third line of the program,
which tries to change the value of the cartTotal variable to 20. The val cartTotal can't be
reassigned to another value (20) after it's been assigned an initial value (0).
Val cannot be reassigned
If you need to update the value of a variable, declare the variable with the Kotlin keyword var, instead
of val.
val keyword - Use when you expect the variable value will not change.
var keyword - Use when you expect the variable value can change.
With val, the variable is read-only, which means you can only read, or access, the value of the variable.
Once the value is set, you cannot edit or modify its value. With var, the variable is mutable, which means
the value can be changed or modified. The value can be mutated.
To remember the difference, think of val as a fixed value and var as variable. In Kotlin, it's recommended
to use the val keyword over the var keyword when possible.
4. Update the variable declaration for cartTotal on line 2 of the program to use var instead of val.
This is how the code should look:
fun main() {
var cartTotal = 0
cartTotal = 20
println("Total: $cartTotal")
}
5. Notice the syntax of the code on line 3 of the program which updates the variable.
cartTotal = 20
Use the assignment operator (=) to assign a new value (20) to the existing variable (cartTotal). You don't
need to use the var keyword again because the variable is already defined.
Using the box analogy, picture the value 20 being stored in the box labeled cartTotal.
Here's a diagram for the general syntax for updating a variable, which has already been declared on an
earlier line of code. Start the statement with the name of the variable you want to update. Add a space, the
equal sign, followed by another space. Then write out the updated value for the variable.
6. Run your program and the code should successfully compile. It should print this output :
Total: 20
7. To see how the variable value changes while the program is running, print the cartTotal variable
to the output after the variable is initially declared. See the code changes below. Line 3 has a
new println() statement. There's also a blank line added on line 4 of the code. Blank lines do not
have any impact on how the compiler understands the code. Add a blank line where it would make
it easier to read your code by separating out related blocks of code.
fun main() {
var cartTotal = 0
println("Total: $cartTotal")
cartTotal = 20
println("Total: $cartTotal")
}
You can see that initially the shopping cart total is 0. Then it updates to 20. You successfully updated a
variable! This was possible because you changed cartTotal from a read-only variable (with val) to a
mutable variable (with var).
Remember that you should only use var to declare a variable if you expect the value to change. Otherwise
you should default to using val to declare a variable. This practice makes your code safer.
Using val ensures that variables won't get updated in your program if you don't expect them to. Once
a val is assigned a value, it always stays that value.
Note: If you are familiar with other programming languages, declaring a val is like declaring a constant
value because it is a read-only variable. There are additional conventions to follow when declaring
constants in Kotlin, which is more advanced for this codelab, but you can find them in
the Constants section of the style guide.
Now you know that a variable must be declared as a var in order to update its value. Apply this knowledge
to the email message example below that should look familiar.
3. Replace the val keyword with the var keyword to make the count variable a mutable variable.
There should be no change in the output when you run the program.
fun main() {
var count: Int = 10
println("You have $count unread messages.")
}
4. However, now you can update the count to a different value. For example, when one new email
arrives in the user's inbox, you can increase count by 1. (You don't need to write the code for the
arrival of an email. Getting data from the internet is a more advanced topic for a much later unit.)
For now, focus on the count variable increasing by 1 with this line of code:
count = count + 1
The expression to the right of the equal sign is count + 1 and evaluates to 11. That is because the current
value of count is 10 (which is on line 2 of the program) and 10 + 1 equals 11. Then with the assignment
operator, the value 11 gets assigned or stored in the count variable.
Add this line of code to your program at the bottom of the main() function. Your code should look like the
following:
fun main() {
var count = 10
println("You have $count unread messages.")
count = count + 1
}
If you run the program now, the output is the same as before because you haven't added any code to use
the count variable after you updated it.
5. Add another print statement that prints out the number of unread messages after the variable has
been updated.
fun main() {
var count = 10
println("You have $count unread messages.")
count = count + 1
println("You have $count unread messages.")
}
6. Run the program. The second message should display the updated count of 11 messages.
You have 10 unread messages.
You have 11 unread messages.
7. For shorthand, if you want to increase a variable by 1, you can use the increment operator (++)
which is made up of two plus symbols. By using these symbols directly after a variable name, you
tell the compiler that you want to add 1 to the current value of the variable, and then store the new
value in the variable. The following two lines of code are equivalent, but using the ++ increment
operator involves less typing.
count = count + 1
count++
Make this modification to your code and then run your program. There should be no spaces between the
variable name and the increment operator.
fun main() {
var count = 10
println("You have $count unread messages.")
count++
println("You have $count unread messages.")
}
8. Run the program. The output is the same, but now you learned about a new operator!
You have 10 unread messages.
You have 11 unread messages.
9. Now modify line 4 of your program to use the decrement operator (--) after the count variable
name. The decrement operator is made up of two minus symbols. By placing the decrement
operator after the variable name, you tell the compiler that you want to decrease the value of the
variable by 1 and store the new value into the variable.
fun main() {
var count = 10
println("You have $count unread messages.")
count--
println("You have $count unread messages.")
}
In this section, you learned how to update a mutable variable using the increment operator (++) and the
decrement operator (--). More specifically, count++ is the same as count = count + 1 and count-- is
the same as count = count - 1.
Back
Next
bug_report Report a mistake
Except as otherwise noted, the content of this page is licensed under the Creative Commons
Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For
details, see the Google Developers Site Policies. Java
Earlier in the codelab, you were introduced to some common basic data types: String, Int, Double,
and Boolean. You just used the Int data type, now you will explore other data types.
String Text
Try these programs in the Kotlin Playground to see what the output is.
Double
When you need a variable with a decimal value, use a Double variable. To learn about its valid range,
refer to this table and look at the decimal digits it can store for example.
Note: The name of the Double data type comes from the data type having double precision compared to
the Float data type, which has single precision. Precision is how many decimal digits they can hold.
Hence, a Double variable can store a more precise value. This table shows more details about the specific
differences between Double and Float types if you're curious. This section of the codelab focuses on
using Double for working with decimal numbers.
Imagine you're navigating to a destination, and your trip is split into three separate parts because you need
to make stops along the way. This program displays the total distance left to reach your destination.
1. Enter this code in the Kotlin Playground. Can you understand what is happening on each line of
code?
fun main() {
val trip1: Double = 3.20
val trip2: Double = 4.10
val trip3: Double = 1.72
val totalTripLength: Double = 0.0
println("$totalTripLength miles left to destination")
}
Three variables called trip1, trip2, and trip3 are declared to represent the distance of each part of the trip.
All of them are Double variables because they store decimal values. Use val to declare each variable
because their values do not change over the course of the program. The program also creates a fourth
variable called totalTripLength which is currently initialized to 0.0. The last line of the program prints a
message with the value of the totalTripLength variable.
2. Fix the code so that the totalTripLength variable is the sum of all three trip lengths.
val totalTripLength: Double = trip1 + trip2 + trip3
The expression on the right of the equal sign evaluates to 9.02 because 3.20 + 4.10 + 1.72 equals 9.02.
The value of 9.02 gets stored into the totalTripLength variable.
fun main() {
val trip1: Double = 3.20
val trip2: Double = 4.10
val trip3: Double = 1.72
val totalTripLength: Double = trip1 + trip2 + trip3
println("$totalTripLength miles left to destination")
}
4. Fix your code to remove the unnecessary Double data type from the variable declarations because
of type inference. The Kotlin compiler can infer that these variables are Double data types based
on the decimal numbers provided as initial values.
fun main() {
val trip1 = 3.20
val trip2 = 4.10
val trip3 = 1.72
val totalTripLength = trip1 + trip2 + trip3
println("$totalTripLength miles left to destination")
}
5. Run your code again to ensure that your code still compiles. The output should be the same, but
now your code is simpler!
String
When you need a variable that can store text, use a String variable. Remember to use quotation marks
around String literal values, such as "Hello Kotlin", whereas the Int and Double literal values do not have
quotes around them.
Notice that there are two String variables declared, a nextMeeting variable and a date variable. Then a
third String variable called reminder is declared, which is set equal to the nextMeeting variable plus
the date variable.
With the + symbol, you can add two strings together, which is called concatenation. The two strings are
combined together, one after the other. The result of the expression, nextMeeting + date is "Next
meeting is:January 1" as shown in the diagram below.
The value "Next meeting is:January 1" is then stored into the reminder variable using the assignment
operator on line 4 of the program.
3. Update your nextMeeting variable to have an extra space at the end of the string before the
closing quotation mark. (Alternatively, you could have added an extra space to the beginning of
the date variable). Your program should look like the following:
fun main() {
val nextMeeting = "Next meeting is: "
val date = "January 1"
val reminder = nextMeeting + date
println(reminder)
}
4. Run your program again and now there should be a space after the colon in the output message.
Next meeting is: January 1
5. Modify the code so that you concatenate - or add - another piece of text to the expression that gets
stored in the reminder variable.
Use the + symbol to add the string literal " at work" to the end of the reminder string.
The code below shows you one way that you could implement the behavior.
fun main() {
val nextMeeting = "Next meeting is: "
val date = "January 1"
val reminder = nextMeeting + date + " at work"
println(reminder)
}
Notice that there are no quotation marks around nextMeeting and date because they are names of
existing string variables (where their respective values are text with quotes around them). Conversely, the
literal " at work" is not previously defined in any variable, so use quotations around this text in order for
the compiler to know that this is a string that should be concatenated onto the other strings.
Technically, you can achieve the same output by declaring a single String variable with the full text
instead of using separate variables. However, the purpose of this exercise is to demonstrate how you can
declare and manipulate String variables, especially how to concatenate separate strings.
7. When reading code that contains strings, you may come across escape sequences. Escape
sequences are characters that are preceded with a backslash symbol (\), which is also called an
escaping backslash.
An example is seeing \" within a string literal like in the below example. Copy and paste this code into the
Kotlin Playground.
fun main() {
println("Say \"hello\"")
}
You learned earlier to use double quotation marks around a string literal. But what if you want to use
the " symbol in your string? Then you need to add the backslash symbol before the double quotation mark
as \" within your string. Remember that there should still be double quotation marks around the whole
string.
In the output, there are quotation marks displayed around hello because we added \" before and
after hello in the println() statement.
For other escape sequences supported in Kotlin, refer to the documentation page on escape sequences. For
example, if you want a new line in your string, use the \ symbol before the character n as in \n.
Now you've learned about concatenating strings and also escape sequences within strings. Move onto the
last data type that this codelab covers.
Boolean
The Boolean data type is useful when your variable only has two possible values represented
by true or false.
An example is a variable that represents whether a device's airplane mode is on or off, or whether an app's
notifications are enabled or disabled.
1. Enter this code in the Kotlin Playground. In line 2 of this program, you declare
a Boolean variable called notificationsEnabled and initialize it to true. Technically, you can
omit : Boolean in the declaration, so you can remove it if you'd like. In line 3 of the program, you
print out the value of the notificationsEnabled variable.
fun main() {
val notificationsEnabled: Boolean = true
println(notificationsEnabled)
}
true
2. Change the initial value of the Boolean to false on line 2 of the program.
fun main() {
val notificationsEnabled: Boolean = false
println(notificationsEnabled)
}
false
3. Other data types can be concatenated to Strings. For example, you can
concatenate Booleans to Strings. Use the + symbol to concatenate (or append) the value of
the notificationsEnabled boolean variable onto the end of the "Are notifications enabled?
" string.
fun main() {
val notificationsEnabled: Boolean = false
println("Are notifications enabled? " + notificationsEnabled)
}
Run the program to see the result of the concatenation. The program should print this output:
You can see that it's possible to set the Boolean variable to a true or false value. Boolean variables
enable you to code more interesting scenarios in which you execute some set of instructions when
a Boolean variable has a true value. Or if the Boolean has a false value, you skip those instructions. You
learn more about Booleans in a future codelab.
Back
Next
bug_report Report a mistake
Except as otherwise noted, the content of this page is licensed under the Creative Commons
Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For
details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and
6. Coding conventions
In the previous codelab, you were introduced to the Kotlin style guide for writing Android code in a
consistent way as recommended by Google and followed by other professional developers.
Here are a couple of other formatting and coding conventions for you to follow based on the new topics
you learned:
Variable names should be in camel case and start with a lowercase letter.
In a variable declaration, there should be a space after a colon when you specify the data type.
There should be a space before and after an operator like the assignment (=), addition (+),
subtraction (-), multiplication (*), division (/) operators and more.
As you write more complex programs, there is a recommended limit of 100 characters per line.
That ensures that you can read all the code in a program easily on your computer screen, without
needing to scroll horizontally when reading code.
// This is a comment.
A comment can also start in the middle of a line of code. In this example, height =
1 is a normal coding statement. // Assume the height is 1 to start with is interpreted as a
comment and not considered part of the code.
height = 1 // Assume the height is 1 to start with
If you want to describe the code in more detail with a long comment that exceeds
100 characters on a line, use a multi-line comment. Start the multi-line comment
with a forward slash (/) and an asterisk symbol (*) as /*. Add an asterisk at the
beginning of each new line of the comment. Then finally end the comment with an
asterisk and forward slash symbol */.
/*
* This is a very long comment that can
* take up multiple lines.
*/
This program contains single-line and multi-line comments that describe what's
happening:
/**
* This program displays the number of messages
* in the user's inbox.
*/
fun main() {
// Create a variable for the number of unread messages.
var count = 10
println("You have $count unread messages.")
As mentioned earlier, you can add blank empty lines to your code to group related
statements together and make the code easier to read.
8. Conclusion
Excellent work! You learned about variables in Kotlin, why variables are useful in
programming, and how to create, update, and use them. You experimented with
different basic data types in Kotlin, including the Int, Double, String, and Boolean data
types. You also learned about the difference between the val and var keywords.
All of these concepts are critical building blocks on your journey to become a
developer.
See you in the next codelab!
Summary
A variable is a container for a single piece of data.
You must declare a variable first before you use it.
Use the val keyword to define a variable that is read-only where the value
cannot change once it's been assigned.
Use the var keyword to define a variable that is mutable or changeable.
In Kotlin, it's preferred to use val over var when possible.
To declare a variable, start with the val or var keyword. Then specify the
variable name, data type, and initial value. For example: val count: Int = 2.
With type inference, omit the data type in the variable declaration if an initial
value is provided.
Some common basic Kotlin data types include: Int, String, Boolean, Float,
and Double.
Use the assignment operator (=) to assign a value to a variable either during
declaration of the variable or updating the variable.
You can only update a variable that has been declared as a mutable variable
(with var).
Use the increment operator (++) or decrement operator (--) to increase or
decrease the value of an integer variable by 1, respectively.
Use the + symbol to concatenate strings together. You can also concatenate
variables of other data types like Int and Boolean to Strings.
Learn more
Variables
Basic types
String templates
Keywords and operators
Basic syntax