Kotlin
I made these notes using the Developer Android Course
We can use the Kotlin playground here to practice.
Hello World in Kotlin
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
Source Developer Android
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 declaration
Source Developer Android
Example
Declaring a function with a return type
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
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
Last updated