Using Higher Order Functions in Kotlin
Create Date: May 18, 2019 at 04:41 PM         | Tag: KOTLIN         | Author Name: Sun, Charles |
Higher oder funciton:
a function that takes another function as an argument
declaring functions:
val action = { println("Hello, World") } val action: () -> Unit = { println("Hello, World") } parameters return val calc = { x: Int, y: Int -> x * y }
val calc: (Int, Int) -> Int = { x, y -> x * y }
function types:
calling functions:
fun<T> first(items: List<T>, predicate: (T) -> Boolean) { for (item in items) { if (predicate(item)) { return item } } throw ... }
declaring and using higher-order fucntions:
val action = { println("Hello, World") } val calc: (Int, Int) -> Int = { x, y -> x * y } fun main() { doSomething(action) println(doAnother(calc(3, 2))) } fun doSomething(func: () -> Unit) { func() } fun doAnother(func: Int): Int { return func }
inlining functions:
- lambdas map to anonymous classes
- extra class and method created each time
- this is expensive
- enter inlining
inline function is more efficient because there is no extra call for a function and just run the code in main import java.lang.Exception fun main() { val ints = listOf(1,2,3,4,5) val i = first(ints, { i -> i == 3 }) println(i) } //inline will be more efficient inline fun <T> first(items: List<T>, predicate: (T) -> Boolean) : T { for (item in items) { if (predicate(item)) { return item } } throw Exception() }
decompile the code using fernflower:
java -jar fernflower.jar out\production\..\InliningKt.class .
not every funciton can inlined
- if lambda is used directly then can inline
- lambda cannot be stored in a variable for later use
- kotlin collection operations are inlined:
- map, filter etc
- The same operations on sequences are not
Kotlin Collection Classes
Create Date: May 18, 2019 at 03:43 PM         | Tag: KOTLIN         | Author Name: Sun, Charles |
Collections:
- collections can be nullable
- collections can hold null values
- collections can be read-only or mutable
- kotlin collections interop with java
- arrays in kotlin
creating collections:
- listOf, setOf, mapOf
- arrayListOf, hashSetOf, hashMapOf
- mutableListOf
- etc...
kotlin collections and java:
- kotlin collections and java collections are the same
- java does not distinguish between mutable and immutable colledctions
collections as platform types:
- when overriding/implementing method...
- is the collection nullable/mutable
- are the members nullable/mutable
Arrays in kotlin:
- array is a class with a type parameter
- can create with
- arrayOf
- arrayOfNulls
- Array() function
Primitive Types:
- each primitive has its own array type
- IntArray
- ByteArray
- CharArray
- etc...
working with arrays in kotlin:
- kotlin provides the same functions on arrays as on collection classes
java class:
package javap; public class Meeting { }
java interface:
package javap; import java.util.List; public interface Organizer { void processMeetings(List<Meeting> meetings); }
two kotlin files:
Program.kt:
package kotlinp import javap.Meeting import javap.Organizer import java.lang.UnsupportedOperationException fun main() { //val people = listOf<Person?>() //val people = listOf(Person(42)) //val people = listOf(Person(42), null) //var people: List<Person?>? = null var people: MutableList<Person?>? = null //listOf() return readonly values, we cannot use add() //people = listOf(Person(42), Person(37), null) people = mutableListOf(Person(42), Person(37)) people.add(null) // for (person in people) { // println(person?.age) // } for (person in people.filterNotNull()) { println(person.age) } } class Person(val age: Int) : Organizer { //MutableList<Meeting>? can be: MutableList<Meeting?>?, List<Meeting>, List<Meeting?) because we are dealing with platform types override fun processMeetings(meetings: MutableList<Meeting>?) { throw UnsupportedOperationException("not implemented") } }
Arrays.kt:
package kotlinp fun main(args: Array<String>) { //not working for (i in args.indices) { println("$i ${args[i]}") } val items = IntArray(2) items[0] = 1 items[1] = 2 val numbers = intArrayOf(1,2,3,4,5) numbers.forEachIndexed { index, element -> println("$index is: $element") } }New Comment
Understand How Nullability Interacts with Your Existing Java Code
Create Date: May 18, 2019 at 12:06 AM         | Tag: KOTLIN         | Author Name: Sun, Charles |
Kotlin understands java annotations
- @Nullable, @NotNull
- javax.annotation
- android.support.annotation
- org.jetbrains.annotation
what if there are no annotations?
- kotlin now working with 'Platform' types
- developer has full responsibility
- String! is a 'Platform' type
What about overriding java types:
- can make the parameters Nullable or not
java class:
package javap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class Meeting { private String title; public void addTitle(@NotNull String title) { this.title = title; } public @Nullable String meetingTitle() { return title; } public String titleCanBeBull() { return title; } }
java interface:
package javap; public interface Address { String getFirstAddress(); }
kotlin functions and classes:
package kotlinp import javap.Address import javap.Meeting fun main() { val m = Meeting() m.addTitle("Title") //with @NotNull, cannot add null. adding null perfectly fine wihtout annotation //m.addTitle(null) val title: String = m.meetingTitle() ?: "noboby" println(title) val t: String? = m.titleCanBeBull() // val i: Int = m.titleCanBeBull() // val i: Int = m.meetingTitle() } class HomeAddress : Address { override fun getFirstAddress(): String { return "" } } class WorkAddress : Address { override fun getFirstAddress(): String? { return "" } }
New Comment