- Basics
- functions defined with keyword “fun”, followed by the name, optional argument list and optional return type
- main function is the entry point to a program
- “Unit“ return type is “void” in Java
- semicolons are optional
- Variables
- declarable by either “var“ or “val“ keywords
- val: variable is immutable (readonly)
- var: variable is mutable (reassignable)
- Type inference: it is not necessary to specify the type of a variable when it gets an value assigned. If not, type specifying is mandatory.
- Data types: predefined types like Int, Boolean, Char are available, which behave like classes!
- Arrays represented by “Array” class
- Creating with “arrayOf()“ or “Array()” class
- declarable by either “var“ or “val“ keywords
- Control Flow
- if-else can be used in assignments: var max = if (a > b) a else b
- no ternary operator as it is possible to use construction above
- “when” is the replacement for “switch“. Syntax is simiar, is also usable as expressions (as for if/else)
- in: to check ranges, e. g. 1.. 7 → println()
- is: whether a variable is a certain type
- for: for (value in 1 .. 10) { ... } for (number in numbers) { … }
- Null safety
- all variables are non-nullable. They can be nullable by assigning a question mark to its type
1var nullable: string? = "John" - Safe call operator: executing member method only when object is not null
- let Operator: using member method in a lambda expression
12val name: string? = nullname.let { println(it.length)} - Elvis operator: fer defing an alternative value if object is null
1val name = nullable ?: "Guest" - not-null assertion: converts nullable type to non-nullable type and throws an Exception (Bad. Do not use)
- Collections and Nullable Types: By default, Collections can’t hold null values. Using the question mark lets collection contain null values:
1val list: List<Int?> = listOf(1,2,null,3) - Notice: this means that elements within the list can be null, not the list itself. Nullable collections can be created by using the question mark after the type name:
1val list: List<Int>? = null - Collections and elements within the collections can be declared together as nullable as well:1val list: List<Int?>? = null
- all variables are non-nullable. They can be nullable by assigning a question mark to its type
- Functions
- general syntax to define a function:123fun functionName (param: Type, ... , paramX TypeX): Type {// here you go!}
- Return type and brackets can be ommited if return value is a single expression1fun avg(a: Double, b: Double) = (a + b) / 2
- “Unit“ type: correspondents to “void” in Java.Functions that return nothing have to return “Unit” (Exception: functions without brackets).
- Default values for parameters: like PHP, Kotlin supports default values for parameters in order to make some of them optional, for example.
- Specifying parameter names when calling a function: Kotlin allows explicitly to name the parameter when calling a function. You can mix named and unnamed arguments but have to call the unnamed parameters first.
- variable number of arguments: “vararg” lets you pass a variable number of arguments to a function. If the function has a second non-vararg parameter, it has to be named during function call.
- 4 types of functions: top level, member, local, internal
- top-level: functions that are defined in a package and usable everywhere (after importing the package)
- member: member methods of a class/object
- local/nested: functions inside functions for more encapsulation and readability.
- internal: usable within a package
- infix notation: str1 matches str2 instead of str1.matches(str2). Creating an infix with keyword “infix” before “fun“.
- general syntax to define a function:
- Classes
- keyword “class“ for defining a class
- Common base class “Any” (like “Object” in Java)
- instantiation without “new” (as in Java/PHP)
- var/val differentiation also available in classes
- property access with dot operator (class.method())
- Constructors: two types: primary and secondary
- Primary Constructor: is part of the class header and declared after class name
- initialization block: introduced with “init” keyword, used for variable initialization for example
- using var/val in constructor arguments makes the variables to object properties.
- Secondary Constructors: defined in the chess (like Java constructors) and must call the primary constructor.
- Default visibility: public; internal visibility enables access within the same package. Further visibilities: private, protected.
- Getter/Setter: Kotlin has internal getters and setters for member variables. It is possible to access the class members with the dot notation and Kotlin will internaly call the getter/setter. Custom getters/setters are also possible.
- Inheritance: by default, all classes are not inheritable unless defined with “open“ before “class“ keyword:
123456open class Computer {// define your members/methods}class Laptop: Computer{//Laptop inherits from Computer} - parent classes must be initialized by child classes, either through primary or secondary constructor
- overriding functions: by default all functions are final, they can be available with {open“ keyword.
- overriding properties: with “open” keyword in base class and “override” in child
- Data classes: getters, setters, equal(), hashcode() methods are generated by Kotlin when using a data class.
1data class Customer (val id: int, val name: String)