« Prev 1 2 3 4 5 6 7 8 9 10 Next »

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:

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

New Comment

Kotlin Collection Classes

Create Date: May 18, 2019 at 03:43 PM         Tag: KOTLIN         Author Name: Sun, Charles

Collections:

creating collections:

kotlin collections and java:

collections as platform types:

Arrays in kotlin:

Primitive Types:

working with arrays in kotlin:

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

what if there are no annotations?

What about overriding java types:

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
« Prev 1 2 3 4 5 6 7 8 9 10 Next »