116: Learning Kotlin – inline, noinline and crossinline

In this episode of learning kotlin, we look at 3 important keywords – inline, noinline and crossinline. The inline keyword is super common and you’ve probably run across this one at some point. What does it mean and when is it useful? We also look at the related but seldom used variants noinline and crossinline.

Download directly

Show Notes

Code Snippets:

Simple inlined function:

// Kotlin 
fun main(args: Array<String>) {
    functionA()
}

inline fun functionA() {
    println("awesomeness !")
}

Warning: Expected performance impact of inlining ‘public inline fun functionA() can be insignificant. Inlining works best for functions with lambda parameters

What the code looks like in Java:

public static final void main(String[] args) {
  String var1 = "awesomeness !";
  System.out.println(var1);
}

Function with lambda parameter:

fun main(args: Array<String>) {
    functionA({
        println("double awesomeness")
    })
}

inline fun functionA(lambda: () -> Unit) {
    println("awesomeness !")
    lambda.invoke()
}

What the code looks like in Java (without inline):

public static final void main(String[] args) {
    functionA(new Function() {
      println("double awesomeness")  
    });
}

public static final void functionA(Function0 lambda) {
    String var1 = "awesomeness !";
    System.out.println(var1);
    lambda.invoke();
}

What the code looks like in Java (with inline):

public static final void main(String[] args) {
    String var1 = "awesomeness !";
    System.out.println(var1);
    String var2 = "double awesomeness";
    System.out.println(var2);
}

Function0:

public interface Function0<out R> : Function<R> {
    /** Invokes the function. */
    public operator fun invoke(): R
}

Misc:

Sponsors

  • Microsoft AppCenter – Sign up now on appcenter.ms and spend less time managing your app lifecycle and more time coding.

Contact

109: Learning Kotlin – Sequences the new Iterables

In this episode of Fragmented, we go back to learning some Kotlin and look at the Iterable like data structure introduced called “Sequences”. What is a sequence? How is it different from Iterable? When should I use it?

Download directly

Show Notes

Eager/Lazy

Eager evaluation:

val lst = listOf(1, 2)
val lstMapped: List<Int> = lst.map { print("$it "); it * it }
print("before sum ")
val sum = lstMapped.sum()

// prints "1 2 before sum"

Lazy evaluation:

val seq = sequenceOf(1, 2)
val seqMapped: Sequence<Int> = seq.map { print("$it "); it * it }
print("before sum ")
val sum = seqMapped.sum()

// prints "before sum 1 2"

Source stackoverflow.com answer

Intermediate and terminal operations

Notice that at each chain operation, a new temporary list is created:

data class Person(val name: String, val age: Int)

fun main(args: Array<String>) {
    val people = 
        listOf(Person("Chris Martin", 31), 
               Person("Will Champion", 32),
               Person("Jonny Buckland", 33),
               Person("Guy Berryman", 34),
               Person("Mhris Cartin", 30))

    println(people
            .filter { it.age > 30 } // new temp. list
            .map {                  
                it.name.split(" ").map {it[0]}.joinToString("")
            }  // new temp. list
            .map { it.toUpperCase() }) // new temp. list
}

Using a sequence:

println(people
        .asSequence()  // convert to sequence
        .filter { it.age > 30 } // lazy eval (intermediate op)
        .map {                  
            it.name.split(" ").map {it[0]}.joinToString("")
        }  // lazy eval (intermediate op)
        .map { it.toUpperCase() }  // lazy eval (intermediate op)
        .toList() // terminal operation
       )

Without a terminal operation, Sequences won’t print anything:

val seq = sequenceOf(1, 2, 3)
println(seq) // prints address
println(seq.toList()) // [1, 2, 3]

You can’t pick an index from a sequence:

println(seq[0]) // throws ERROR "No get method providing array access"
println(seq.toList()[0]) // 1

Sponsors

Contact

101: Learning Kotlin – visibility modifiers, internal modifier, modules

Another day, another opportunity to learn more Kotlin. In this episode, Kaushik walks through the concept of visibility modifiers. How do the modifiers in Kotlin differ from the ones in Java? What is this new internal modifier? When should I use each of the operators?

Listen on to find out!

Direct download

Shownotes:

  • Excellent resource explaining visibility modifiers in Kotlin

    open class Outer {
        private val a = 1
        protected open val b = 2
        internal val c = 3
        val d = 4  // public by default
    
        protected class Nested {
            public val e: Int = 5
        }
    }
    
    class Subclass : Outer() {
        // a is not visible
        // b, c and d are visible
        // Nested and e are visible
    
        override val b = 5   // 'b' is protected
    }
    
    class Unrelated(o: Outer) {
        // o.a, o.b are not visible
        // o.c and o.d are visible (same module)
        // Outer.Nested is not visible, and Nested::e is not visible either 
    }
    

092: Learning Kotlin – dealing with static-ness and (companion) objects costs

In this second episode of our learning Kotlin series, we talk about Kotlin’s support for static members or … lack thereof. Kotlin as a language was designed so that there’s no such thing as a “static member” in a class but there are times when having static members can be useful.

So what do we do in those cases? do we just avoid static members? are there better alternatives? what are the costs with some of these approaches?

Listen on to find out more!

Download directly

Show Notes

Static alternatives

Cost of approaches

Look at the end of these notes for code snippets

Misc:

Sponsors

Contact

Code snippets

Cost effectiveness

// ----------------------------------------
// THIS IS BAD
class Foo {
    companion object {
        val myVar = "testing"
    }
}

// calling from Kotlin
Foo.myVar

// calling from Java
Foo.Companion.getMyVar();  // yuck

// ----------------------------------------
// THIS IS OK

// notice the Jvm annotation
class Foo {
    companion object {
        @JvmField val myVar = "testing"
    }
}

// calling from Kotlin
Foo.myVar

// calling from Java
Foo.myVar; 

// ----------------------------------------
// THIS IS AWESOME

// notice the const keyword
class Foo {
    companion object {
        const val myVar = "testing"
    }
}

// calling from Kotlin
Foo.myVar

// calling from Java 
Foo.myVar; 
// compiler additionally inlines this

// myVar is not a primitive or String?
// use @JvmField or @JvmStatic for methods

Package level options

// inside BottomSheetView.Kt
class BottomSheetView {
    companion object {
        const val BOTTOM_SHEET_ANIMATION_TIMING = 500L
    }

    // ...
}


// accessed as:
animation.setTiming(BottomSheetView.BOTTOM_SHEET_ANIMATION_TIMING)

// ----------------------------------------
// INSTEAD DO THIS

// inside BottomSheetView.Kt
const val BOTTOM_SHEET_ANIMATION_TIMING = 500L

class BottomSheetView {
    // ...
}

// accessed as:
animation.setTiming(BottomSheetViewKt.BOTTOM_SHEET_ANIMATION_TIMING)

089: Learning Kotlin – Properties a first class language feature

In this mini Fragment, KG talks about his journey learning Kotlin as a newb. Given that Kotlin is most likely going to be the de-facto language for most developers, it makes sense to deepen our understanding of the language (as we have strived with Java over the years).

“Properties” in Kotlin are a first class language feature. But what does that actually mean? What are the nifty features we get with properties? How are these resolved from a Java class when there’s potential a name clash? What are some other gotchas and learnings from using properties? Listen on to find out:

Direct download

Shownotes:

Contact