Lock in $30 Savings on PRO—Offer Ends Soon! ⏳

Kotlin Idioms in Android

Nevin
August 06, 2017

Kotlin Idioms in Android

Nevin

August 06, 2017
Tweet

More Decks by Nevin

Other Decks in Technology

Transcript

  1. Variables val addressDist: String = "Da Tong Dist” val addressDist1

    = "Da Tong Dist" addressDist1 = "XXX Dist" var addressDist2 = "Da Tong Dist” addressDist2 = null var addressDist3: String? = "Da Tong Dist” addressDist3 = null println(addressDist3?.length) println(addressDist3?.length ?: "empty") null safety immutability if not null if not null else can skip // Error! // Error! // OK! // Nullable String
  2. Loops and Range for(a in 1..100) {
 println(a)
 }
 


    val numbers = 1..100
 
 for (a in numbers) {
 print(a)
 }
 
 for (a in 100 downTo 1) {
 println(a)
 }
 
 for (b in 100 downTo 1 step 5) {
 
 } Range
  3. Conditionals fun test(value: Any){ val whenValue = when (value) {


    "matching" -> {
 println("Matched!")
 println("Second statement")
 "As Expected"
 }
 is String -> {
 println("Not matched bug it's ${result.length} words")
 "Try again"
 }
 else -> {
 println("Others")
 "Wrong type"
 }
 }
 println(whenValue) } Smart Cast When Everything is an expression (can return value)
  4. Safe Cast // Unsafe: May throw exception var unSafeButton: Button

    = view.findViewById(R.id.forward) as Button // Safe: Will return null if cast fail var safeButton: Button? = view.findViewById(R.id.forward) as? Button Safe Cast
  5. Function fun hello(): Unit {
 println("Hello")
 } fun returnsAFour(): Int

    {
 return 4
 } fun returnsAFour()= 4 fun sum(x: Int, y: Int, z: Int = 0, w: Int = 0) = x + y + z + w
 sum(x = 1, y = 0, z = 4, w = 6) void can be inferred default value named argument
  6. Function fun reallyPrintingStrings(vararg strings: String) {
 for (string in strings)

    {
 println(string)
 }
 } 
 fun main(args: Array<String>) {
 printStrings("1")
 printStrings("1", "2")
 printStrings("1", "2", "3")
 printStrings("1", "2", "3", "4")
 } variable number of arguments
  7. Class // Java public final class Person { public Person(@Nullable

    String name, int age) { } } // Kotlin class Person(name: String?, age: Int) fun main(.....){ val nevin = Person("Mary", 33) }
  8. Class public final class Person { @Nullable private String name;

    private int age; @Nullable public final String getName() { return this.name; } public final void setName(@Nullable String var1) { this.name = var1; } public final int getAge() { return this.age; } public final void setAge(int var1) { this.age = var1; } public Person(@Nullable String name, int age) { this.name = name; this.age = age; } } class Person(name: String?, age: Int) { var name = name var age = age }
  9. Class public final class Person { @NotNull private String name;

    private int age; @NotNull public final String getName() { return this.name; } public final void setName(@NotNull String var1) { Intrinsics.checkParameterIsNotNull(var1, "<set-?>"); this.name = var1; } public final int getAge() { return this.age; } public final void setAge(int var1) { this.age = var1; } public Person(@NotNull String name, int age) { Intrinsics.checkParameterIsNotNull(name, "name"); super(); this.name = name; this.age = age; } } class Person(var name: String, var age: Int) Kotlin class has only property ( with getter and setter)
  10. Class public final class Person { @NotNull private String name;

    private final int age; @NotNull public final String getName() { return this.name; } public final void setName(@NotNull String var1) { Intrinsics.checkParameterIsNotNull(var1, "<set-?>"); this.name = var1; } public Person(@NotNull String name, int age) { Intrinsics.checkParameterIsNotNull(name, "name"); super(); this.name = name; this.age = age; } } class Person(var name: String, private val age: Int) mark private if you want to hide it no new constructor
  11. Data Class public final class Person { // skip… @NotNull

    public final String component1() { return this.name; } public final int component2() { return this.age; } @NotNull public final Person copy(@NotNull String name, int age) { Intrinsics.checkParameterIsNotNull(name, "name"); return new Person(name, age); } // $FF: synthetic method // $FF: bridge method @NotNull public static Person copy$default(Person var0, String var1, int var2, int var3, Object var4) { if((var3 & 1) != 0) { var1 = var0.name; } if((var3 & 2) != 0) { var2 = var0.age; } return var0.copy(var1, var2); } public String toString() { return "Person(name=" + this.name + ", age=" + this.age + ")"; } public int hashCode() { return (this.name != null?this.name.hashCode():0) * 31 + this.age; } public boolean equals(Object var1) { if(this != var1) { if(var1 instanceof Person) { Person var2 = (Person)var1; if(Intrinsics.areEqual(this.name, var2.name) && this.age == var2.age) { return true; } } return false; } else { return true; } data class Person(var name: String, var age: Int) equals hasCode toString copy destructuring data
  12. Data Clas • Can extends other class open class Cat

    : RealmObject() { var name: String? = null } ^_^
  13. Object public final class Author { @NotNull private static String

    name; public static final Author INSTANCE; @NotNull public final String getName() { return name; } public final void setName(@NotNull String var1) { Intrinsics.checkParameterIsNotNull(var1, "<set-?>"); name = var1; } private Author() { INSTANCE = (Author)this; name = "Nevin"; } static { new Author(); } } object Author { var name ="Nevin" } singleton println(Author.name) usage
  14. Lazy Delegation val name by lazy{ println("initializing...") "Value" } fun

    main(args: Array<String>) { println("first run:$name") println("second run:$name") println("third run:$name") } initializing… first run:value first run:value first run:value
  15. Observable Delegation var name by Delegates.observable("Empty") { prop, old, new

    -> println("$old => $new") } fun main(args: Array<String>) { name = "first" name = "second" } empty => first first => second
  16. • Null Safety • Immutable • Range • When •

    Smart / Safe Cast • Data Class • Object • Function You’ve Learned: Kotlin Basics
  17. Lambda val sum = { a: Int, b: Int ->

    a + b } fun sum(a: Int, b: Int) = a + b Function Literal input output
  18. Lambda val sum: (Int, Int) -> Int = { a,

    b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) } Higher-Order Function input output explicit type take functions as parameter
  19. Higher-Order Function val sum: (Int, Int) -> Int = {

    a, b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) }
  20. Higher-Order Function val sum: (Int, Int) -> Int = {

    a, b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) }
  21. Higher-Order Function val sum: (Int, Int) -> Int = {

    a, b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) } op(3, 4, sum) op(3, 4, { a, b -> a + b })
  22. Higher-Order Function val sum: (Int, Int) -> Int = {

    a, b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) } op(3, 4, sum) op(3, 4, { a, b -> a + b })
  23. Higher-Order Function val sum: (Int, Int) -> Int = {

    a, b -> a + b } fun op(num1: Int, num2: Int, func: (Int, Int) -> Int) { val answer = func(num1, num2) } op(3, 4, { a: Int, b: Int -> a + b }) val sum = { a: Int, b: Int -> a + b }
  24. Higher-Order Function op(3, 4) { a: Int, b: Int ->

    a + b } move lambda argument out of parentheses
  25. Higher-Order Function listOf(4, 5, 6).filter() { i: Int -> i

    > 5 } move lambda argument out of parentheses
  26. Higher-Order Function listOf(4, 5, 6).filter { i: Int -> i

    > 5 } remove unnecessary parentheses from function all with lambda
  27. Higher-Order Function listOf(4, 5, 6).filter { it -> it >

    5 } Use “it” to represent the parameter
  28. Higher-Order Function listOf(4, 5, 6).filter { it > 5 }

    remove “it” if there’s only a single parameter
  29. FirefoxData-Android • Sync with Firefox safely • Only you can

    see your data Lazy Delegation Lambda Null Safety [See detail steps here]
  30. Other Mozilla Project • FirefoxData-Android [Kotlin Ready!] • The privacy

    browser [Kotlin is coming] • Firefox for Android [Official] [For Git Users]