Android con Kotlin

Sebastian Tellez

twitter: @gorrotowi

github: gorrotowi

blog: blog-gorrotowi.rhcloud.com

Que es Kotlin?

Statically typed programming language
for the JVM, Android and the browser

100% interoperable with Java

Por que necesitamos kotlin?

  • Programación defensiva
  • Lambdas, clases anónimas
  • minSDK 19

Como se ve kotlin

fun sum(a:Int, b:Int):Int{
    return a + b
}
fun sum(a:Int, b:Int) = a + b

Extension functions

static boolean isMonday(Date date){
    return date.getDay() = 1;
}

boolean monday = DateUtils.isMonday(date);
fun Date.isMonday():Boolean{
        return getDay() == 1
    }

val monday = date.isMonday()
fun isMonday():Boolean{
    return day == 1
}

fun isMonday() = day == 1

Function Expressions

{x, y -> x + y}

val sum: (Int,Int) -> Int = {x,y -> x + y}

{x:Int, y:Int -> x + y}

val sum = {x:Int, y:Int -> x + y}

Function Expressions

fun apply(one:Int, two:Int, func:(Int, Int) -> Int):Int{
    return func(one, two)
}

val sum = apply(4,2, {x, y -> x + y})
val difference = apply(4,2, {x, y -> x - y})
val sum = apply(4,2) {x, y -> x + y}
val difference = apply(4,2) {x, y -> x - y}

Function Expressions

fun Int.apply(other:Int, func:(Int, Int) -> Int):Int{
    return func(this, other)
}

val sum = 4.apply(2) {x, y -> x + y}
val difference = 4.apply(2) {x, y -> x - y}
val sum = apply(4,2) {x, y -> x + y}
val difference = apply(4,2) {x, y -> x - y}

Function Expressions

fun Int.apply(func:(Int) -> Int):Int{
    return func(this)
}

val double = 1.apply {x -> x * 2}
val double = 1.apply {it * 2}

Extension Function Expressions

db.beginTransaction();
try{
    db.delete("users", "first_name = ?", new String[]{"Sebastian"});
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}
fun SQLiteDatabase.inTransaction(func: () -> Unit){
    beginTransaction()
    try{
      func()
      setTransactionSuccessful()  
    } finally{
      endTransaction()
    }
}

db.inTransaction {
    db.delete("users", "first_name = ?", arrayOf("Sebastian"))
}

Extension Function Expressions

fun SQLiteDatabase.inTransaction(func: (SQLiteDatabase) -> Unit){
    beginTransaction()
    try{
      func(this)
      setTransactionSuccessful()  
    } finally{
      endTransaction()
    }
}

db.inTransaction {
    it.delete("users", "first_name = ?", arrayOf("Sebastian"))
}

Extension Function Expressions

fun SQLiteDatabase.inTransaction(func: SQLiteDatabase.() -> Unit){
    beginTransaction()
    try{
      func()
      setTransactionSuccessful()  
    } finally{
      endTransaction()
    }
}

db.inTransaction {
    delete("users", "first_name = ?", arrayOf("Sebastian"))
}

Android con Kotlin

By Sebastian Gorro Towi

Android con Kotlin

  • 604