0% found this document useful (0 votes)
12 views

Lesson 1 Kotlin basics (1)

Uploaded by

Dương Khánh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Lesson 1 Kotlin basics (1)

Uploaded by

Dương Khánh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

Click + Create New Project to start a new project.

Select Kotlin and JVM | IDEA, and click Next.


Name the project and click Next.
Select Tools > Kotlin > Kotlin REPL to open the REPL.
Enter the code below into the REPL:

fun printHello() {

println("Hello World")

Commands that you type into the REPL are interpreted as soon as you press
Ctl+Enter (Cmd+Enter on a Mac). Let's take a quick look at the Kotlin code in this
slide.

● The fun keyword designates a function, followed by the name.


● As with other programming languages, the parentheses are for function
arguments, if any, and the curly braces frame the code for the function.
● There is no return type because the function doesn't return anything.
● Note that there are no semicolons at the ends of lines. If you're used to adding
them, that's OK. You can either add them or leave them out.
Let's start exploring Kotlin by having a look at its main elements, starting with numeric
operators. As with other languages, Kotlin uses +, -, *, / and % for plus, minus,
times, division and modulus (or remainder). There’s also the increment and
decrement operators, comparison operators, assignment operator, and equality
operators.
Math operators are very straightforward, and behave just as you would expect based
on other programming languages.
Kotlin supports different number types, such as Int, Long, Double, and Float. Notice
that they all start with an initial cap in the output. Although they may not be objects in
the internal representation, they are objects in the sense that we can call member
functions and properties on them, and Kotlin represents objects using initial caps.
More on this later.
Integer types in Kotlin are the same standard size as other languages.
Let's look at the non-integer numeric types: Double, Float, Char, and Boolean
(including the boolean operators).
Results of operations keep the types of the operands, so 1/2 = 0, but 1.0/2.0 = 0.5.
Transition: 1 click

Kotlin does not implicitly convert between number types, so you can't assign a Short
value directly to a Long variable, or a Byte to an Int. Implicit number conversion is
a common source of errors in programs, but you can avoid that by assigning values of
different types with casting.

Here we create a variable and first show what happens if you try to reassign it with a
type mismatch. We then use toByte() to cast it and print it without errors.
Strings are a sequence of characters enclosed by double quotes that may also
contain spaces and numbers. Strings are immutable.

When a string appears literally in source code, it is known as a string literal or an


anonymous string. Kotlin has two types of string literals: escaped strings that may
have escaped characters in them, and raw strings that can contain newlines and
arbitrary text. A raw string is delimited by a triple quote ("""), contains no escaping
and can contain newlines and any other characters.
Strings in Kotlin work pretty much like strings in any other programming language
using " for strings and ' for single characters, and you can concatenate strings with
the + operator.

You can create string templates by combining them with values. In this example,
$numberOfDogs and $numberOfCats are replaced with the value of those
variables. This is called variable interpolation.
Transition: 1 click

String literals can contain template expressions; pieces of code that are evaluated
and whose results are concatenated into the string.
As in other languages, a value can be the result of an expression. Use curly braces
{} to define the expression.
Kotlin has powerful type inference, and usually you just let the compiler do the work
by inferring it. However, you can explicitly declare the type of a variable. Kotlin does
not enforce immutability, though it is recommended. In essence use val over var.
The type you store in a variable is inferred when the compiler can figure it out from
context. If you want, you can also specify the type of a variable explicitly, using colon
notation.

Some things to note about colon notation:

● The data type comes after the variable name


● Always put a space after :
Kotlin supports two types of variables: changeable and unchangeable. With var, you
can assign a value, then change the value later in the program. With val, you can
assign a value once. If you try to change it to something else, you get an error.

Kotlin does not enforce immutability, though it is recommended. In essence use val
over var.
Let’s look at an example. You can assign the count variable a value, then assign it a
new value, because it is defined with var. Trying to assign a new value to size gives
an error because it is defined with val.

Note that in Kotlin, by default, variables cannot be null. We'll talk about null safety a
bit later in this lesson.
The most common conditional is an if/else statement. If statements let you
specify a block of code (the code within the curly braces following the if) that is
executed only if a given condition is true. If the condition is false, then the code
specified by an else statement is executed. Note that the else block is not required.
As in other languages, you can have multiple cases by using else if. Note that you
can use any comparison or equality operator in the if / else conditions, not just ==
or < as shown above. You can also use logical and ("&&"), and logical or ("||")
operators. See the slide on Operators for more information.
A range (or "interval") defines the inclusive boundaries around a contiguous span of
values of some comparable type, such as an intRange (for example, integers from 1
to 100 inclusive). The first number is the start point, the second number is the
endpoint.

All ranges are bounded, and the left side of the range is always <= the right side of
the range.

Although the implementation itself is immutable, there is no restriction that objects


stored must also be immutable. If mutable objects are stored here, then the range
effectively becomes mutable.
In Kotlin, the condition you test can use ranges, too. Ranges let you specify a subset
of a larger group, so here, for example, we're only concerned with integers between 1
and 100. (i.e., a range of values of type Int, or IntRange). There are equivalent
classes to IntRange for each of the other types, such as CharRange and
LongRange.

Optional
You can also define a step size between the bounding elements of the range. For
example, in 1..8, if we defined a step size of 2, our range would include the elements
1, 3, 5, 7. (see Ranges).

Example:
for (i in 1..8 step 2) print(i)
=>1357
There's a nicer way to write a series of if/else statements in Kotlin, using the when
statement. It's a bit like the "switch" statement in other languages. Conditions in a
when statement can also use ranges.

Resource:
● See When Expression
Kotlin supports for loops, while loops, do-while loops. Let’s look at examples of
each one starting with for loops.

Here, we use a for loop to iterate through the array and print the elements.
In Kotlin, you can loop through the elements and the indexes at the same time.
You can specify ranges of numbers or characters, alphabetically. As in other
languages, you don't have to step forward by 1. You can define the step size. You
can also step backward using downTo.
Transition: 1 click

Like other languages, Kotlin has while loops, do...while loops, and ++ and --
operators.
Kotlin also has repeat loops that let you repeat a block of code that follows inside its
curly braces. The number in parentheses is the number of times it should be
repeated. This print command is executed twice.
A list is an ordered collection with access to its elements via indices—integer
numbers that reflect their position. Elements can occur more than once in a list.
Lists created with listOf() cannot be changed (immutable).
Next, we'll use mutableListOf to create a list that can be changed. In the example,
the remove() method returns true when it successfully removes the item passed.

Note that in the result ("kotlin.Boolean"), Boolean starts with an initial cap because it's
an object. Although you'll see it in REPL, for subsequent slides, we'll omit the type in
the result for clarity.
Arrays are used to organize data so that a related set of values can be easily sorted
or searched.
Like other languages, Kotlin has arrays. Unlike lists in Kotlin, which have mutable and
immutable versions, there is no mutable version of an Array. Once you create an
array, the size is fixed. You can't add or remove elements, except by copying to a new
array.

Declare an array of strings using arrayOf(). Use the


java.util.Arrays.toString() array utility to print it out.

Note that you can also add "import java.util.Arrays" and then use
"println(Arrays.toString(school)" to print it.

The rules about using val and var are the same with arrays as for lists.
You can declare arrays with a mix of types, or just one type for all the elements. In the
second example, although we define an array of only integers using intArrayOf().
There are corresponding builders, or instantiation functions, for arrays of other types.
In this example, we combine the two arrays and then println the resulting array.
Be sure to add import java.util.Arrays as a header if you have not already
done so.

Note that operator overloading is happening in the background and that + is calling
operator fun plus(other:IntArray) : IntArray

numbers2.plus(numbers) would generate the same result as numbers2 +


numbers
A hallmark of Kotlin, is its attempt to eliminate the danger of null references in code.
Null references occur when code attempts to access a variable that doesn't refer to
anything, potentially stopping code execution and causing a
NullPointerException.
Let's talk about nullable versus non-nullable variables. Programming errors involving
nulls have been the source of countless bugs. Kotlin seeks to reduce bugs by
introducing non-nullable variables. Because variables cannot be null by default, there
is less risk of code code execution failing due to NullPointerExceptions. The
line of code above, for example, is not allowed by the compiler.
That took care of the error. When you have complex data types, such as a list:
● You can allow the elements of the list to be null.
● You can allow for the list to be null, but if it's not null its elements cannot be
null.
● You can allow both the list or the elements to be null.
Transition: 1 click

You can test for null with the ? operator, saving you the pain of writing many
if/else statements.

Although the first example is written in Kotlin, it's more the way you might test for null
in Java or other languages. It's still in Kotlin, but it's not the idiomatic Kotlin way to do
it. The last line of code in the example simply says "call dec() on numberOfBooks if
it's not null."
If you really love NullPointerExceptions, Kotlin lets you keep them. The not-null
assertion operator, !! (double-bang), converts any value to a non-null type and
throws an exception if the value is null.

In programming slang, the exclamation mark is often called a "bang," so the not-null
assertion operator is sometimes called the "double-bang" or "bang bang" operator.

Warning: Because !! will throw an exception, it should only be used when it would
be exceptional to hold a null value.
The example is shorthand for:

"if numberOfBooks is not null, decrement and use it; otherwise use the value after
the ?:, which is 0."

If numberOfBooks is null, evaluation is stopped, and the dec() method is not


called. Combining the null tests with the elvis operator reduces them to a single line,
and avoids having to use a longer if/else statement.

Resource:
● Elvis Operator

You might also like