Lesson 1 Kotlin basics (1)
Lesson 1 Kotlin basics (1)
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.
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.
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.
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.
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.
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
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."
Resource:
● Elvis Operator