0% found this document useful (0 votes)
3 views69 pages

Android Developer

This document serves as a guide for building Android apps using the Kotlin programming language, emphasizing its productivity benefits and stability. It introduces basic programming concepts, including defining and calling functions, and provides instructions for using the Kotlin Playground to run simple programs. Additionally, it outlines Google's coding standards for Kotlin source files, focusing on naming conventions, special characters, and file structure.

Uploaded by

kolarovnickolai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views69 pages

Android Developer

This document serves as a guide for building Android apps using the Kotlin programming language, emphasizing its productivity benefits and stability. It introduces basic programming concepts, including defining and calling functions, and provides instructions for using the Kotlin Playground to run simple programs. Additionally, it outlines Google's coding standards for Kotlin source files, focusing on naming conventions, special characters, and file structure.

Uploaded by

kolarovnickolai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

1.

Before you begin

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.

Kotlin is a modern programming language that helps developers be more productive.


For example, Kotlin allows you to be more concise and write fewer lines of code for
the same functionality compared to other programming languages. Apps that are
built with Kotlin are also less likely to crash, resulting in a more stable and robust
app for users. Essentially, with Kotlin, you can write better Android apps in a shorter
amount of time. As a result, Kotlin is gaining momentum in the industry and is the
language that the majority of professional Android developers use.

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.

What you'll build


 Short programs in Kotlin that display messages when you run them.

What you'll learn


 How to write and run a simple Kotlin program.
 How to modify a simple program to change the output.

What you'll need


 A computer with internet access and a web browser.

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!

3. Open Kotlin Playground


In a web browser on your computer, open the Kotlin Playground.

You should see a web page similar to this image:


There's already some default code populated in the code editor. These three lines of
code make up a simple program:

fun main() {
println("Hello, world!")
}

Even if you've never programmed before, can you guess what the program does?

See if your guess is correct by moving onto the next section!

4. Run your first program

Click to 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.

4. Run your first program

Click to 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.

Now you may be wondering, what is a function?


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.

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.

Define versus call a function

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

These are the key parts needed to define a function:

 The function needs a name, so you can call it later.

 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:

 The function definition starts with the word fun.

 Then the name of the function is main.

 There are no inputs to the function, so the parentheses are empty.

 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.

Example function names:

 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 ().

Here are some examples of functions with a different number of inputs:

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

6. Modify your program


1. In order to change the message that's displayed in the output, modify
the println() function call on the second line of the program.
Replace world with Android in the println() function. Make sure that "Hello,
Android!" is still within quotation marks and within the parentheses.

fun main() {
println("Hello, Android!")
}

2. Run the program.


3. The output should show this message:

Hello, Android!

Nice job, you modified your first program!

Now can you change your code so that the message gets printed twice? See the
desired output:

Hello, Android!
Hello, Android!

Print more than one message


You can put as many lines of instructions inside a function as you need to accomplish
a task. However, note that there should only be one statement per line in Kotlin. If
you want to write another statement, put it on a new line of the function.

To change your program to print multiple lines of text:

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.

4. Change the code so that it says Hello, YOUR_NAME!.

Kotlin style guide


bookmark_border
 On this page
 Source files
o Naming
o Special Characters
o Structure
 Formatting
o Braces
o Whitespace
o Specific constructs

This document serves as the complete definition of Google’s Android
coding standards for source code in the Kotlin Programming Language. A
Kotlin source file is described as being in Google Android Style if and only
if it adheres to the rules herein.

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).

Last update: 2021-05-19

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:

 All other whitespace characters in string and character literals are


escaped.
 Tab characters are not used for indentation.

Special escape sequences

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

For the remaining non-ASCII characters, either the actual Unicode


character (e.g., ∞) or the equivalent Unicode escape (e.g., \u221e) is used.
The choice depends only on which makes the code easier to read and
understand. Unicode escapes are discouraged for printable characters at
any location and are strongly discouraged outside of string literals and
comments.

Example Discussion

val unitAbbrev = "μs" Best: perfectly clear even without a comment.


val unitAbbrev = "\ Poor: there’s no reason to use an escape with a printable character.
u03bcs" // μs
val unitAbbrev = "\u03bcs" Poor: the reader has no idea what this is.
return "\ufeff" + content Good: use escapes for non-printable characters, and comment if necessary.
Structure
A .kt file comprises the following, in order:

 Copyright and/or license header (optional)


 File-level annotations
 Package statement
 Import statements
 Top-level declarations

Exactly one blank line separates each of these sections.

Copyright / License

If a copyright or license header belongs in the file it should be placed at


the immediate top in a multi-line comment.

/*
* Copyright 2017 Google, Inc.
*
* ...
*/

Do not use a KDoc-style or single-line-style comment.

/**
* 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

Import statements for classes, functions, and properties are grouped


together in a single list and ASCII sorted.

Wildcard imports (of any type) are not allowed.

Similar to the package statement, import statements are not subject to a


column limit and they are never line-wrapped.

Top-level declarations

A .kt file can declare one or more types, functions, properties, or type
aliases at the top-level.

The contents of a file should be focused on a single theme. Examples of


this would be a single public type or a set of extension functions
performing the same operation on multiple receiver types. Unrelated
declarations should be separated into their own files and public
declarations within a single file should be minimized.

No explicit restriction is placed on the number nor order of the contents of


a file.

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.

Class member 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 // WRONG


else doLotsOfProcessingOn(string, otherParametersHere)

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:

 No line break before the opening brace.


 Line break after the opening brace.
 Line break before the closing brace.
 Line break after the closing brace, only if that brace terminates a
statement or terminates the body of a function, constructor,
or named class. For example, there is no line break after the brace if
it is followed by else or a comma.

return Runnable {
while (condition()) {
foo()
}
}

return object : MyClass() {


override fun foo() {
if (condition()) {
try {
something()
} catch (e: ProblemException) {
recover()
}
} else if (otherCondition()) {
somethingElse()
} else {
lastThing()
}
}
}

A few exceptions for enum classes are given below.

Empty blocks

An empty block or block-like construct must be in K&R style.

try {
doSomething()
} catch (e: Exception) {} // WRONG!

try {
doSomething()
} catch (e: Exception) {
} // Okay

Expressions

An if/else conditional that is used as an expression may omit braces only if


the entire expression fits on one line.

val value = if (string.isEmpty()) 0 else 1 // Okay

val value = if (string.isEmpty()) // WRONG!


0
else
1

val value = if (string.isEmpty()) { // Okay


0
} else {
1
}

Indentation

Each time a new block or block-like construct is opened, the indent


increases by four spaces. When the block ends, the indent returns to the
previous indent level. The indent level applies to both code and comments
throughout the block.

One statement per line

Each statement is followed by a line break. Semicolons are not used.

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

 Command lines in a comment that may be cut-and-pasted into a


shell

Where to break

The prime directive of line-wrapping is: prefer to break at a higher


syntactic level. Also:

 When a line is broken at an operator or infix function name, the


break comes after the operator or infix function name.
 When a line is broken at the following “operator-like” symbols, the
break comes before the symbol:
 The dot separator (., ?.).
 The two colons of a member reference (::).
 A method or constructor name stays attached to the open
parenthesis (() that follows it.
 A comma (,) stays attached to the token that precedes it.
 A lambda arrow (->) stays attached to the argument list that
precedes it.
Note: The primary goal for line wrapping is to have clear code, not
necessarily code that fits in the smallest number of lines.

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.

fun <T> Iterable<T>.joinToString(


separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = ""
): String {
// …
}

Expression functions

When a function contains only a single expression it can be represented


as an expression function.

override fun toString(): String {


return "Hey"
}

override fun toString(): String = "Hey"

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.

var directory: File? = null


set(value) {
// …
}

Read-only properties can use a shorter syntax which fits on a single line.
val defaultExtension: String get() = "kt"

Whitespace
Vertical

A single blank line appears:

 Between consecutive members of a class: properties, constructors,


functions, nested classes, etc.
 Exception: A blank line between two consecutive properties
(having no other code between them) is optional. Such blank
lines are used as needed to create logical groupings of
properties and associate properties with their backing
property, if present.
 Exception: Blank lines between enum constants are covered
below.
 Between statements, as needed to organize the code into logical
subsections.
 Optionally before the first statement in a function, before the first
member of a class, or after the last member of a class (neither
encouraged nor discouraged).
 As required by other sections of this document (such as
the Structure section).

Multiple consecutive blank lines are permitted, but not encouraged or


ever required.

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) {
}

 Separating any reserved word, such as else or catch, from a closing


curly brace (}) that precedes it on that line.

// WRONG!
}else {
}

// Okay
} else {
}

 Before any open curly brace ({).

// WRONG!
if (list.isEmpty()){
}

// Okay
if (list.isEmpty()) {
}

 On both sides of any binary operator.

// WRONG!
val two = 1+1

// Okay
val two = 1 + 1

This also applies to the following “operator-like” symbols:


 the arrow in a lambda expression (->).
// WRONG!
ints.map { value->value.toString() }

// 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

 the dot separator (.).

// WRONG
it . toString()

// Okay
it.toString()

 the range operator (..).

// WRONG
for (i in 1 .. 4) print(i)

// Okay
for (i in 1..4) print(i)

 Before a colon (:) only if used in a class declaration for specifying a


base class or interfaces, or when used in a where clause for generic
constraints.

// 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>

 After a comma (,) or colon (:).

// WRONG!
val oneAndTwo = listOf(1,2)

// Okay
val oneAndTwo = listOf(1, 2)

// WRONG!
class Foo :Runnable

// Okay
class Foo : Runnable

 On both sides of the double slash (//) that begins an end-of-line


comment. Here, multiple spaces are allowed, but not required.

// WRONG!
var debugging = false//disabled by default

// Okay
var debugging = false // disabled by default

This rule is never interpreted as requiring or forbidding additional space at


the start or end of a line; it addresses only interior space.

Specific constructs

Enum classes

An enum with no functions and no documentation on its constants may


optionally be formatted as a single line.

enum class Answer { YES, NO, MAYBE }


When the constants in an enum are placed on separate lines, a blank line
is not required between them except in the case where they define a
body.

enum class Answer {


YES,
NO,

MAYBE {
override fun toString() = """¯\_(ツ)_/¯"""
}
}

Since enum classes are classes, all other rules for formatting classes
apply.

Annotations

Member or type annotations are placed on separate lines immediately


prior to the annotated construct.

@Retention(SOURCE)
@Target(FUNCTION, PROPERTY_SETTER, FIELD)
annotation class Global

Annotations without arguments can be placed on a single line.

@JvmField @Volatile
var disposable: Disposable? = null

When only a single annotation without arguments is present, it may be


placed on the same line as the declaration.

@Volatile var disposable: Disposable? = null

@Test fun selectAll() {


// …
}

@[...] 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

Implicit return/property types

If an expression function body or a property initializer is a scalar value or


the return type can be clearly inferred from the body then it can be
omitted.

override fun toString(): String = "Hey"


// becomes
override fun toString() = "Hey"

private val ICON: Icon = IconLoader.getIcon("/icons/kotlin.png")


// becomes
private val ICON = IconLoader.getIcon("/icons/kotlin.png")

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+.

Special prefixes or suffixes, like those seen in the


examples name_, mName, s_name, and kName, are not used except in the
case of backing properties (see Backing properties).

Package Names

Package names are all lowercase, with consecutive words simply


concatenated together (no underscores).

// 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.

Underscores are permitted to appear in test function names to separate


logical components of the name.

@Test fun pop_emptyStack() {


// …
}

Functions annotated with @Composable that return Unit are PascalCased


and named as nouns, as if they were types.

@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

Constant names use UPPER_SNAKE_CASE: all uppercase letters, with


words separated by underscores. But what is a constant, exactly?

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.

const val NUMBER = 5


val NAMES = listOf("Alice", "Bob")
val AGES = mapOf("Alice" to 35, "Bob" to 32)
val COMMA_JOINER = Joiner.on(',') // Joiner is immutable
val EMPTY_ARRAY = arrayOf()

These names are typically nouns or noun phrases.

Constant values can only be defined inside of an object or as a top-level


declaration. Values otherwise meeting the requirement of a constant but
defined inside of a class must use a non-constant name.

Constants which are scalar values must use the const modifier.

Non-constant names

Non-constant names are written in camelCase. These apply to instance


properties, local properties, and parameter names.

val variable = "var"


val nonConstScalar = "non-const"
val mutableCollection: MutableSet = HashSet()
val mutableElements = listOf(mutableInstance)
val mutableValues = mapOf("Alice" to mutableInstance, "Bob" to mutableInstance2)
val logger = Logger.getLogger(MyClass::class.java.name)
val nonEmptyArray = arrayOf("these", "can", "change")

These names are typically nouns or noun phrases.

Backing properties

When a backing property is needed, its name should exactly match that of
the real property except prefixed with an underscore.

private var _table: Map? = null

val table: Map


get() {
if (_table == null) {
_table = HashMap()
}
return _table ?: throw AssertionError()
}

Type variable names

Each type variable is named in one of two styles:

 A single capital letter, optionally followed by a single numeral (such


as E, T, X, T2)
 A name in the form used for classes, followed by the capital
letter T (such as RequestT, FooBarT)

Camel case

Sometimes there is more than one reasonable way to convert an English


phrase into camel case, such as when acronyms or unusual constructs like
“IPv6” or “iOS” are present. To improve predictability, use the following
scheme.

Beginning with the prose form of the name:

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.

Prose form Correct Incorrect

"XML Http Request" XmlHttpRequest XMLHTTPRequest


"new customer ID" newCustomerId newCustomerID
Prose form Correct Incorrect

"inner stopwatch" innerStopwatch innerStopWatch


"supports IPv6 on iOS" supportsIpv6OnIos supportsIPv6OnIOS
"YouTube importer" YouTubeImporter YoutubeImporter*

(* Acceptable, but not recommended.)

Note: Some words are ambiguously hyphenated in the English language:


for example “nonempty” and “non-empty” are both correct, so the
method names checkNonempty and checkNonEmpty are likewise both correct.
Documentation
Formatting

The basic formatting of KDoc blocks is seen in this example:

/**
* Multiple lines of KDoc text are written here,
* wrapped normally…
*/
fun method(arg: String) {
// …
}

...or in this single-line example:

/** An especially short bit of KDoc. */

The basic form is always acceptable. The single-line form may be


substituted when the entirety of the KDoc block (including comment
markers) can fit on a single line. Note that this only applies when there
are no block tags such as @return.

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.

This is a fragment–a noun phrase or verb phrase, not a complete


sentence. It does not begin with "A `Foo` is a...", or "This method returns...",
nor does it have to form a complete imperative sentence like " Save the
record.". However, the fragment is capitalized and punctuated as if it were
a complete sentence.

Usage

At the minimum, KDoc is present for every public type, and


every public or protected member of such a type, with a few exceptions
noted below.

Exception: Self-explanatory functions

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”.

It is not appropriate to cite this exception to justify omitting relevant


information that a typical reader might need to know. For example, for a
function named getCanonicalName or property named canonicalName, don’t
omit its documentation (with the rationale that it would say only /**
Returns the canonical name. */) if a typical reader may have no idea what
the term "canonical name" means!

Exception: overrides

8. Fix errors in your code


When you learn a human language, there are rules of syntax and grammar for the
correct way to use words and form sentences. Similarly, for programming languages,
there are specific rules for what makes valid code, which means code that compiles
successfully.

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.

Error message from Kotlin Playground

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!".

3. Run the program again.

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!

3. Copy and paste this program into the Kotlin Playground.


fun main() {
println("Tuesday")
println("Thursday")
println("Wednesday")
println("Friday")
println("Monday")
}

Fix the program so that it prints this output:

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:

There is a chance of snow

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:

How's the weather today?

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

2. The code in your program should look like:


fun main() {
println("I'm")
println("learning")
println("Kotlin!")
}

3. This is the correct code for the program:


fun main() {
println("Monday")
println("Tuesday")
println("Wednesday")
println("Thursday")
println("Friday")
}

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:

How's the weather today?


Back

2. Variables and data types


In computer programming, there's the concept of a variable, which is a container for a single piece of data.
You can envision it as a box that contains a value. The box has a label, which is the name of the variable.
By referring to the box by its name, you have access to the value it holds.

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.

Have a nice day!

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 ____ .

Have a nice day!

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 } .

Have a nice day!

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.

Example app with variables

Let's look at an app example to see where it may use variables.


In a maps app, you may find a details screen for each location, such as a restaurant or business. The above
screenshot from the Google Maps app shows the details for Google's company headquarters, which is
called the Googleplex. Which pieces of data do you think are stored as variables in the app?

 Name of the location

 Star rating of the location

 Number of reviews of the location

 Whether the user saved (or bookmarked) this location

 Address of the location

 Description of the location

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.

Kotlin data What kind of data it can contain Example lit


type values

String Text "Add conta


"Search"
"Sign in"

Int Integer number 32


1293490
-59281

Double Decimal number 2.0


501.0292
-31723.999

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.

 Number of reviews of the location is a whole number, so it should be stored as an Int.

 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.

 Address of the location is text, so it should be a String.

 Description of the location is also text, so it should be a String.

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:

 Name of the video (String)

 Name of the channel (String)

 Number of views on the video (Int)


 Number of likes on the video (Int)

 Number of comments on the video (Int)

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:

 Name of the sender (String)

 Subject of the email (String)

 Whether the email is starred (Boolean)

 Number of new emails in the inbox (Int)

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.

3. Guess what data type those variables are.

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.

In the main function of a program:

 Create an integer cartTotal variable that starts at the value 0.


 The user adds a sweater that costs $20 to their shopping cart.

 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")
}

2. Run the program, and you will get a compile error.

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")
}

8. Run the program again and the output should be:


Total: 0
Total: 20

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.

Increment and decrement operators

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.

1. Replace the code in the Kotlin Playground with this program:


fun main() {
val count: Int = 10
println("You have $count unread messages.")
}

2. Run the program. It should print out:


You have 10 unread messages.

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.")
}

10. Run the program. It should print this output:


You have 10 unread messages.
You have 9 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

5. Explore other data types

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.

Kotlin data type What kind of data it can contain

String Text

Int Integer number


Double Decimal number

Boolean true or false (only two possible values)

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.

Your whole program should look like the below code:

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")
}

3. Run the program. It should print this out:


9.02 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.

1. Copy and paste this program into the Kotlin Playground.


fun main() {
val nextMeeting = "Next meeting is:"
val date = "January 1"
val reminder = nextMeeting + date
println(reminder)
}

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.

2. Run your program. It should print this out:


Next meeting is:January 1
When you concatenate two strings together, there are no extra spaces added between the strings. If you
want a space after the colon in the resulting string, you need to add the space to one string or the other.

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.

6. Run the program.

It should print this output:

Next meeting is: January 1 at work

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.

8. Run the program to see the output. It should show:


Say "hello"

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)
}

Run the program, and it should print this out:

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)
}

Run the program, and it should print this out:

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:

Are notifications enabled? false

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.

7. Commenting in your code


When coding, another good practice to follow is to add comments that describe what
the code is intended to do. Comments can help people who read your code follow it
more easily. Two forward slash symbols, or //, indicate that the text after it on the
rest of the line is considered a comment, so it isn't interpreted as code. It's common
practice to add a space after the two forward slash symbols.

// 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.")

// Decrease the number of messages by 1.


count--
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.

1. Add some comments to an earlier code snippet that you used.


2. Run the program to ensure that the behavior didn't change because
comments shouldn't affect the output.

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

You might also like