Please enable JavaScript.
Coggle requires JavaScript to display documents.
kotlin (Basic synctax (Functions (fun sum(a: Int, b: Int) : Int {
return…
kotlin
Basic synctax
-
Functions
fun sum(a: Int, b: Int) : Int {
return a + b
}
fun sum(a:Int, b:Int):Unit{
println("sum of $a and $b is ${a+b}")
}
fun sum(a:Int, b:Int) = a + b
Variables: use val and var
- val is variable only read and assign value only once time
- var is variable more times
Ex: val a : Int = 3
val b = 2 // Inferred type integer
val c : Int // not init value variable
String templates:
using expression in string variable
Example:
val a = "1 is integer"
val b = "${a.replace("is", "was")}"
Check null using == or != null
Ex: if (a == null) {// TODO}
Nullable values using ? after type
Ex: fun convertInteger(a : string) : Int?
-> Can return null value if a don't contain number
Ranges using keyword in
, step
, downTo
, until
Ex: if (x in 1..5)
for (x in 9 downTo 0) // 9 -> 0
for (x in 0 until 10) // 0 -> 9
for (x in 1..5 step 2) // x is 1, 3, 5
Loop
-
-
Using when
same as switch case
Ex: when(string){
string.toUpperCase -> // TODO
string.toLowerCase -> // TODO
}
Basic
Array:
Init:
- arrayOf(1,2,3)
- val numbers = IntArray(5)
- val b: IntArray(5) = intArrayOf(1,2,3,4,5)
- array can contain element has different types
Ex val b = arrayOf(5, "abc)"
- array can contain other array
Ex val b = array(arrayOf(2,3), arrayOf(2,3,4))
Primitive types: IntArray, ShortArray, ByteArray
Dynamic set value for array
Ex: val numbers = IntArray(5)
numbers[0] = 1
numbers.set(0, 1)
-
Method support:
- average
- max, min
- sum
- count
- find, findLast
- filter
- sortedArray(), sortedArrayDescending()
...
Loop:
Ex: numbers.forEach({ e -> print("$e ") })
- numbers.forEachIndexed({i, e -> println("numbers[$i] = $e")})
- numbers.iterator()
- for( number in numbers) {// TODO}
Returns and jump
Return: By default returns from the nearest enclosing function
- Only return: return value for function or return terminal func
- Return with label: jump to the label
- Return with anonymous func: jump out and terminal the func
-
-
-
Interface
Properties:
- Can not custom setter method
- Can not set init value for properties
- Can custom getter for
val
property and don't custom for var
property
- Class implementation must override properties don't have init value
Function
- Can have body or not
- Class implementation must override function don't have body
Extensions
Ex: fun receiver_type.method_name() {//TODO}
val receiver_type.property_name : type // cannot init because it don't have backing field
- It placed on the top level, under the package
- If the class had member name as same as the member extension name, the priority for member name will higher
Functions and Lambdas
Functions
Infix:
- Must be member function or extension function
- Must have a single parameter, only one parameter
- Priority only higher than boolean operator such as ||, &&, is or in
- Using infix method to clear code, readable and near natural language
Using varargs parameter:
- May has only one varargs parameter in function
- Varargs parameter accept pass array , list data of type parameter
Inline functions:
- Using keyword
inline
before functions
- Can access with another member has public and protected modifier
- Help improve performance , eliminate the memory overhead, the complier will copied the function to the call site.
- Inline properties: it copied to the call site as same as inline function
High-order function:
- Allow using another function as a parameter
Ex: val plus = {(a: Int, b: Int) -> a + b}
fun plusNumber(calculator: (a: Int, b: Int) 0> Int) {
plus(4,7)
}
- Allow return a function:
ex: fun plusNumber() : ((Int, Int) -> Int) {
return ::plus
}
Collections
List: listOf and mutableListOf
- Store list items by indices
- The item can duplicated
- MutableListOf can add, remove items
Set: setOf and mutableSetOf
- Store unique items
- Compare 2 list set, don't care index
only items have value equals and same size
Map: set of key-value pair
Key is unique, value can duplicated
- Compare 2 maps equals is have key-value in map equal key-value in another map and have same size, don't care indices
Iterator: complete each step for the whole collection and then proceeds to the next step
Sequence: perform all the processing steps one-by-one for every single element.
Operators
Transformation:
- Mapping
- Zipping: zip and unzip
- Association
Association:
- with: create a map which elements of original collection are key of map, and value produces from them
Aggregate: Fold and Reduce
- Fold need init value and can progress empty collection
- Reduce use first and second element to init and start progress, will throw exception if progress empty collection
Language Constructs
Destructuring declarations:
- Work only data class, map, lambda
Ex: val (name, age) = user
with user is data class
Equality
- ==: compare the value of primitive declaration or value object of the data class
- ===: compare reference of two objects and value of primitive declarations
- equals: compare content of variable same as ==, but different in case of Float and Double comparison
Ex: a = -0.0, b =0.0
a.equals(b): false
a == b: true
Exception:
- try and catch and finally. Finally always executes irrespective of whether an exception is handled or not by the catch block
- try catch is expression, can use to value return
Ex: val name = user?.name ?: throw("user not found")
fun div(a: Int, b: Int): Any {
try {a/b}
catch(e: Exception) { println("Divide by zero not allowed) }
}
- Throw exception
-
-
Call Kotlin from Java
properties complied to Java elements:
- getter method: name of method is name of properties with get prefix
- setter method: name of method is name of properties with set prefix
Moreover, if name of properties start with is
, the getter method is name of this properties, and the setter method is name of properties and replace is
to set
Package-level functions
The generate class name of Java can change use annotation JvmName("className")
- If JvmName of multiple file has same name, add one more annotation UseJvmMultiFIle below JvmName annotation -> help JVM generate all members in multi file in only one file
-