Kotlin

I made these notes using the Developer Android Course

  • We can use the Kotlin playground here to practice.

Hello World in Kotlin

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

Style guide

  • Function names should be in camel case and should be verbs or verb phrases.

  • Each statement should be on its own line.

  • The opening curly brace should appear at the end of the line where the function begins.

  • There should be a space before the opening curly brace.

  • The function body should be indented in by 4 spaces. Do not use a tab character to indent your code, type in 4 spaces.

  • The closing curly brace is on its own line after the last line of code in the function body. The closing brace should line up with the fun keyword at the beginning of the function.

  • See the full Kotlin style guide here

Variables

Data Types

data types

Source Developer Android

Declaration

declaration

Source Developer Android

  • Variables that can be reassigned use the var keyword.

  • Constants have to be declared using val

  • val keyword - Use when you expect the variable value will not change.

  • var keyword - Use when you expect the variable value can change.

  • Constants in Kotlin here

Comments

Functions

function syntax

Function declaration

Declare function

Source Developer Android

  • Example

Declaring a function with a return type

Declare fun with return

Source Developer Android

  • Example

The Unit type

By default, if you don't specify a return type, the default return type is Unit. Unit means the function doesn't return a value. Unit is equivalent to void return types in other languages

Store a function in a var

Function with parameter(s)

  • Declaration

declare a function with a parameter

Source Developer Android

  • Example with one parameter

  • Example with multiple parameters

⚠️ Warning: Unlike in some languages, such as Java, where a function can change the value passed into a parameter, parameters in Kotlin are immutable. You cannot reassign the value of a parameter from within the function body.

Function with default arguments

  • Example

Resources

Official Android Training courses
Kotlin Documentation
W3Schools Kotlin Tutorial

Last updated