1 of 59

1

1

1

Lesson 1:

Kotlin basics

This work is licensed under the Apache 2 license.

Android Development with Kotlin v1.0

This work is licensed under the Apache 2 license.

2 of 59

About this lesson

Lesson 1: Kotlin basics

2

Android Development with Kotlin

This work is licensed under the Apache 2 license.

3 of 59

Get started

3

Android Development with Kotlin

This work is licensed under the Apache 2 license.

4 of 59

Open IntelliJ IDEA

4

Android Development with Kotlin

This work is licensed under the Apache 2 license.

5 of 59

Create a new project

5

Android Development with Kotlin

This work is licensed under the Apache 2 license.

6 of 59

Name the project

6

Android Development with Kotlin

This work is licensed under the Apache 2 license.

7 of 59

Open REPL (Read-Eval-Print-Loop)

7

It may take a few moments before the Kotlin menu appears under Tools.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

8 of 59

Create a printHello() function

8

Press Control+Enter (Command+Enter on a Mac) to execute.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

9 of 59

Operators

9

Android Development with Kotlin

This work is licensed under the Apache 2 license.

10 of 59

Operators

  • Mathematical operators
  • Assignment operator
  • Equality operators
  • Increment and decrement operators
  • Comparison operators

10

  • - * / %

=

== !=

++ --

< <= > >=

Android Development with Kotlin

This work is licensed under the Apache 2 license.

11 of 59

Math operators with integers

1 + 1 =>

2

53 - 3 =>

50

50 / 10 =>

5

9 % 3 =>

0

11

Android Development with Kotlin

This work is licensed under the Apache 2 license.

12 of 59

Math operators with doubles

1.0 / 2.0 =>

0.5

2.0 * 3.5 =>

7.0

12

Android Development with Kotlin

This work is licensed under the Apache 2 license.

13 of 59

Math operators

1+1

⇒ kotlin.Int = 2

13

indicates output from your code.

Result includes the type (kotlin.Int).

2.0*3.5

⇒ kotlin.Double = 7.0

1.0/2.0

⇒ kotlin.Double = 0.5

50/10

⇒ kotlin.Int = 5

53-3

⇒ kotlin.Int = 50

Android Development with Kotlin

This work is licensed under the Apache 2 license.

14 of 59

Numeric operator methods

Kotlin keeps numbers as primitives, but lets you call methods on numbers as if they were objects.

14

2.4.div(2)

⇒ kotlin.Double = 1.2

3.5.plus(4)

⇒ kotlin.Double = 7.5

2.times(3)

⇒ kotlin.Int = 6

Android Development with Kotlin

This work is licensed under the Apache 2 license.

15 of 59

Data types

15

Android Development with Kotlin

This work is licensed under the Apache 2 license.

16 of 59

Integer types

16

Type

Bits

Notes

Long

64

From -263 to 263-1

Int

32

From -231 to 231-1

Short

16

From -32768 to 32767

Byte

8

From -128 to 127

Android Development with Kotlin

This work is licensed under the Apache 2 license.

17 of 59

Floating-point and other numeric types

17

Type

Bits

Notes

Double

64

16 - 17 significant digits

Float

32

6 - 7 significant digits

Char

16

16-bit Unicode character

Boolean

8

True or false. Operations include:

|| - lazy disjunction, && - lazy conjunction,

! - negation

Android Development with Kotlin

This work is licensed under the Apache 2 license.

18 of 59

Operand types

Results of operations keep the types of the operands

18

6.0*50

⇒ kotlin.Double = 300.0

6.0*50.0

⇒ kotlin.Double = 300.0

6*50

⇒ kotlin.Int = 300

1/2

⇒ kotlin.Int = 0

1.0*2.0

⇒ kotlin.Double = 0.5

Android Development with Kotlin

This work is licensed under the Apache 2 license.

19 of 59

Type casting

Assign an Int to a Byte

Convert Int to Byte with casting

19

val i: Int = 6

println(i.toByte())

⇒ 6

val i: Int = 6

val b: Byte = i

⇒ error: type mismatch: inferred type is Int but Byte was expected

println(b)

Android Development with Kotlin

This work is licensed under the Apache 2 license.

20 of 59

Underscores for long numbers

Use underscores to make long numeric constants more readable.

val oneMillion = 1_000_000

val idNumber = 999_99_9999L

val hexBytes = 0xFF_EC_DE_5E

val bytes = 0b11010010_01101001_10010100_10010010

20

Android Development with Kotlin

This work is licensed under the Apache 2 license.

21 of 59

Strings

Strings are any sequence of characters enclosed by double quotes.

val s1 = "Hello world!"

String literals can contain escape characters

val s2 = "Hello world!\n"

Or any arbitrary text delimited by a triple quote (""")

val text = """

var bikes = 50

"""

21

Android Development with Kotlin

This work is licensed under the Apache 2 license.

22 of 59

String concatenation

val numberOfDogs = 3

val numberOfCats = 2

22

=> I have 3 dogs and 2 cats

"I have $numberOfDogs dogs" + " and $numberOfCats cats"

Android Development with Kotlin

This work is licensed under the Apache 2 license.

23 of 59

String templates

A template expression starts with a dollar sign ($) and can be a simple value:

val i = 10

println("i = $i")

=> i = 10

23

Or an expression inside curly braces:

val s = "abc"

println("$s.length is ${s.length}")

=> abc.length is 3

Android Development with Kotlin

This work is licensed under the Apache 2 license.

24 of 59

String template expressions

val numberOfShirts = 10

val numberOfPants = 5

24

=> I have 15 items of clothing

"I have ${numberOfShirts + numberOfPants} items of clothing"

Android Development with Kotlin

This work is licensed under the Apache 2 license.

25 of 59

Variables

25

Android Development with Kotlin

This work is licensed under the Apache 2 license.

26 of 59

Variables

  • Powerful type inference
  • Mutable and immutable variables

26

  • Let the compiler infer the type
  • You can explicitly declare the type if needed
  • Immutability not enforced, but recommended

Kotlin is a statically-typed language. The type is resolved at compile time and never changes.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

27 of 59

Specifying the variable type

Colon Notation

var width: Int = 12

var length: Double = 2.5

27

Important: Once a type has been assigned by you or the compiler, you can't change the type or you get an error.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

28 of 59

Mutable and immutable variables

  • Mutable (Changeable)

  • Immutable (Unchangeable)

28

var score = 10

val name = "Jennifer"

Although not strictly enforced, using immutable variables is recommended in most cases.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

29 of 59

var and val

var count = 1

count = 2

29

val size = 1

size = 2

=> Error: val cannot be reassigned

Android Development with Kotlin

This work is licensed under the Apache 2 license.

30 of 59

Conditionals

30

Android Development with Kotlin

This work is licensed under the Apache 2 license.

31 of 59

Control flow

31

Kotlin features several ways to implement conditional logic:

  • If/Else statements
  • When statements
  • For loops
  • While loops

Android Development with Kotlin

This work is licensed under the Apache 2 license.

32 of 59

if/else statements

val numberOfCups = 30

val numberOfPlates = 50

32

=> Not enough cups!

if (numberOfCups > numberOfPlates) {

println("Too many cups!")

} else {

println("Not enough cups!")

}

Android Development with Kotlin

This work is licensed under the Apache 2 license.

33 of 59

if statement with multiple cases

val guests = 30

if (guests == 0) {

println("No guests")

} else if (guests < 20) {

println("Small group of people")

} else {

println("Large group of people!")

}

33

⇒ Large group of people!

Android Development with Kotlin

This work is licensed under the Apache 2 license.

34 of 59

Ranges

  • Data type containing a span of comparable values (e.g., integers from 1 to 100 inclusive)

34

  • Ranges are bounded
  • Objects within a range can be mutable or immutable

Android Development with Kotlin

This work is licensed under the Apache 2 license.

35 of 59

Ranges in if/else statements

35

=> 50

val numberOfStudents = 50

if (numberOfStudents in 1..100) {

println(numberOfStudents)

}

Note: There are no spaces around the "range to" operator (1..100)

Android Development with Kotlin

This work is licensed under the Apache 2 license.

36 of 59

when statement

when (results) {

0 -> println("No results")

in 1..39 -> println("Got results!")

else -> println("That's a lot of results!")

}

36

⇒ That's a lot of results!

As well as a when statement, you can also define a when expression that provides a return value.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

37 of 59

for loops

val pets = arrayOf("dog", "cat", "canary")

for (element in pets) {

print(element + " ")

}

37

⇒ dog cat canary

You don’t need to define an iterator variable and increment it for each pass.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

38 of 59

for loops: elements and indexes

for ((index, element) in pets.withIndex()) {

println("Item at $index is $element\n")

}

38

⇒ Item at 0 is dog

Item at 1 is cat

Item at 2 is canary

Android Development with Kotlin

This work is licensed under the Apache 2 license.

39 of 59

for loops: step sizes and ranges

for (i in 1..5) print(i)

⇒ 12345

39

for (i in 5 downTo 1) print(i)

⇒ 54321

for (i in 3..6 step 2) print(i)

⇒ 35

for (i in 'd'..'g') print (i)

⇒ defg

Android Development with Kotlin

This work is licensed under the Apache 2 license.

40 of 59

while loops

var bicycles = 0

while (bicycles < 50) {

bicycles++

}

println("$bicycles bicycles in the bicycle rack\n")

40

⇒ 49 bicycles in the bicycle rack

do {

bicycles--

} while (bicycles > 50)

println("$bicycles bicycles in the bicycle rack\n")

⇒ 50 bicycles in the bicycle rack

Android Development with Kotlin

This work is licensed under the Apache 2 license.

41 of 59

repeat loops

repeat(2) {

print("Hello!")

}

41

⇒ Hello!Hello!

Android Development with Kotlin

This work is licensed under the Apache 2 license.

42 of 59

Lists and arrays

42

Android Development with Kotlin

This work is licensed under the Apache 2 license.

43 of 59

Lists

  • Lists are ordered collections of elements

43

  • Elements can occur more than once in a list
  • List elements can be accessed programmatically through their indices

An example of a list is a sentence: it's a group of words, their order is important, and they can repeat.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

44 of 59

Immutable list using listOf()

Declare a list using listOf() and print it out.

val instruments = listOf("trumpet", "piano", "violin")

println(instruments)

44

⇒ [trumpet, piano, violin]

Android Development with Kotlin

This work is licensed under the Apache 2 license.

45 of 59

Mutable list using mutableListOf()

Lists can be changed using mutableListOf()

val myList = mutableListOf("trumpet", "piano", "violin")

myList.remove("violin")

45

With a list defined with val, you can't change which list the variable refers to, but you can still change the contents of the list.

⇒ kotlin.Boolean = true

Android Development with Kotlin

This work is licensed under the Apache 2 license.

46 of 59

Arrays

  • Arrays store multiple items

46

  • Array elements can be accessed programmatically through their indices
  • Array elements are mutable
  • Array size is fixed

Android Development with Kotlin

This work is licensed under the Apache 2 license.

47 of 59

Array using arrayOf()

An array of strings can be created using arrayOf()

val pets = arrayOf("dog", "cat", "canary")

println(java.util.Arrays.toString(pets))

47

With an array defined with val, you can't change which array the variable refers to, but you can still change the contents of the array.

⇒ [dog, cat, canary]

Android Development with Kotlin

This work is licensed under the Apache 2 license.

48 of 59

Arrays with mixed or single types

An array can contain different types.

val mix = arrayOf("hats", 2)

48

An array can also contain just one type (integers in this case).

val numbers = intArrayOf(1, 2, 3)

Android Development with Kotlin

This work is licensed under the Apache 2 license.

49 of 59

Combining arrays

Use the + operator.

val numbers = intArrayOf(1,2,3)

val numbers2 = intArrayOf(4,5,6)

val combined = numbers2 + numbers

println(Arrays.toString(combined))

49

=> [4, 5, 6, 1, 2, 3]

Android Development with Kotlin

This work is licensed under the Apache 2 license.

50 of 59

Null safety

50

Android Development with Kotlin

This work is licensed under the Apache 2 license.

51 of 59

Null safety

51

  • In Kotlin, variables cannot be null by default
  • Allow null-pointer exceptions using the !! operator
  • You can test for null using the elvis (?:) operator
  • You can explicitly assign a variable to null using the safe call operator

Android Development with Kotlin

This work is licensed under the Apache 2 license.

52 of 59

Variables cannot be null

52

Declare an Int and assign null to it.

var numberOfBooks: Int = null

⇒ error: null can not be a value of a non-null type Int

In Kotlin, null variables are not allowed by default.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

53 of 59

Safe call operator

Declare an Int? as nullable

var numberOfBooks: Int? = null

53

The safe call operator (?), after the type indicates that a variable can be null.

In general, do not set a variable to null as it may have unwanted consequences.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

54 of 59

Testing for null

Check whether the numberOfBooks variable is not null. Then decrement that variable.

54

Now look at the Kotlin way of writing it, using the safe call operator.

var numberOfBooks = 6

if (numberOfBooks != null) {

numberOfBooks = numberOfBooks.dec()

}

var numberOfBooks = 6

numberOfBooks = numberOfBooks?.dec()

Android Development with Kotlin

This work is licensed under the Apache 2 license.

55 of 59

The !! operator

If you’re certain a variable won’t be null, use !! to force the variable into a non-null type. Then you can call methods/properties on it.

55

throws NullPointerException if s is null

val len = s!!.length

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

Android Development with Kotlin

This work is licensed under the Apache 2 license.

56 of 59

Elvis operator

Chain null tests with the ?: operator.

numberOfBooks = numberOfBooks?.dec() ?: 0

56

The ?: operator is sometimes called the "Elvis operator," because it's like a smiley on its side with a pompadour hairstyle, like Elvis Presley styled his hair.

Android Development with Kotlin

This work is licensed under the Apache 2 license.

57 of 59

Summary

57

Android Development with Kotlin

This work is licensed under the Apache 2 license.

58 of 59

Summary

58

In Lesson 1, you learned how to:

Android Development with Kotlin

This work is licensed under the Apache 2 license.

59 of 59

Pathway

Practice what you’ve learned by�completing the pathway:

Lesson 1: Kotlin basics

59

Android Development with Kotlin

This work is licensed under the Apache 2 license.