Building android apps with kotlin

29
Developing Android apps with Kotlin AVGeeks, June 2016 Shem Magnezi

Transcript of Building android apps with kotlin

Page 1: Building android apps with kotlin

Developing Android apps

with KotlinAVGeeks, June 2016

Shem Magnezi

Page 2: Building android apps with kotlin

Shem Magnezi@shemag8 | shem8.github.com

Page 3: Building android apps with kotlin

Java is great

▣ Very popular.▣ Great community.▣ Lots of frameworks and libraries.▣ Supported by big companies (Oracle &

Google).▣ Portable, fast, well documented.▣ Great IDEs▣ You can write server side, web and mobile.

Page 4: Building android apps with kotlin

Yes but...

▣ Lot’s of boilerplate▣ Null checks▣ Exception handling▣ Function pointers▣ Data classes (POJO)▣ Extension functions▣ Operator overloading▣ String interpolation▣ And more...

Page 5: Building android apps with kotlin

On Android it even worse

▣ Barely support Java 8 (N+)▣ Partially support Java 7 (KitKat+)▣ There are some libraries that fill some of the

missing features (retro lambda, RX, etc..) but it’s not the same.

▣ It mainly feel too ‘heavy’ for front end code.

Page 6: Building android apps with kotlin

Kotlin

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

100% interoperable with Java™

Page 7: Building android apps with kotlin

Kotlin?

▣ Open source, lead by JetBrains.▣ JVM language (Like Scala, Groovy and Clojure)▣ Can call Java code and vice versa.▣ Fully integrated IDE.▣ Small (600KB before ProGuard).▣ Statically typed so no runtime overhead.▣ Used by a lot of big companies, even by the

Android team (data binding).

Page 8: Building android apps with kotlin

Code!

Page 9: Building android apps with kotlin

1.Basic syntax

Page 10: Building android apps with kotlin

when (x) {

in 1..10 -> print("x is in the range")

in validNumbers -> print("x is valid")

!in 10..20 -> print("x is outside the range")

else -> print("none of the above")

}

fun mul(x: Int, y: Int = 2): Int {

return x * y

}

fun mul(x: Int, y: Int = 2) = x * y

view.setOnClickListener({ //click handling })

Page 11: Building android apps with kotlin

if (obj is String) {

print(obj.length)

}

val items = listOf(1, 2, 3, 4)

items.first() == 1

items.last() == 4

items.filter { it % 2 == 0 } // returns [2, 4]

ints.forEach {

if (it == 0) return

print(it)

}

Page 12: Building android apps with kotlin

2.Null Safety

Page 13: Building android apps with kotlin

‘’I call it my billion-dollar mistake. It was the invention of the null reference in 1965 ... My goal was to ensure that all use of references should be absolutely safe... This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

Tony Hoare

Page 14: Building android apps with kotlin

var a: String = "abc"

a = null // compilation error

var b: String? = "abc"

b = null // ok

val l = b?.length ?: -1

Page 15: Building android apps with kotlin

3.Data Classes

Page 16: Building android apps with kotlin

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

You get for free:

▣ equals()

▣ hashCode()

▣ toString() of the form "User(name=John, age=42)",

▣ copy() function

▣ getters()

Page 17: Building android apps with kotlin

4.Extensions

Functions

Page 18: Building android apps with kotlin

fun Date.isThuesday() Boolean {

return day == 2

}

if (date.isTuesday) {

...

}

fun Date.isThuesday() = day == 2

Page 19: Building android apps with kotlin

fun SQLiteDatabase.inTransaction(func: () -> Unit) {

beginTransaction()

try {

func()

setTransactionSuccessful()

} finally {

endTransaction()

}

}

db.inTransaction {

}

Page 20: Building android apps with kotlin

fun AppCompatActivity.navigate(frag: Fragment) {

val fragmentTransaction = supportFragmentManager.beginTransaction()

fragmentTransaction.replace(content.id, frag);

fragmentTransaction.commit();

}

fun Fragment.userError(msg: String?) {

Snackbar.make(view, msg, Snackbar.LENGTH_LONG).show()

}

Page 21: Building android apps with kotlin

fun SharedPreferences.edit(func:SharedPreferences.Editor.(): Unit) {

val editor = edit()

editor.func()

editor.apply()

}

fun SharedPreferences.Editor.set(pair: Pair<String, String>) = putString(pair.first, pair.second)

preferences.edit {

set("foo" to "bar")

set("fizz" to "buzz")

remove("username")

}

Page 22: Building android apps with kotlin

inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) {

viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {

override fun onGlobalLayout() {

if (measuredWidth > 0 && measuredHeight > 0) {

viewTreeObserver.removeOnGlobalLayoutListener(this)

f()

}

}

})

}

recycler.afterMeasured {

val columnCount = width / columnWidth

layoutManager = GridLayoutManager(context, columnCount)

}

Page 23: Building android apps with kotlin

5.Android

Extensions

Page 24: Building android apps with kotlin

// Using R.layout.activity_main from the main source set

import kotlinx.android.synthetic.main.activity_main.*

public class MyActivity : Activity() {

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

setContentView(R.layout.activity_main)

textView.setText("Hello, world!") // Instead of findView(R.id.textView) as TextView

}

}

Page 25: Building android apps with kotlin

6.Anko library

Page 26: Building android apps with kotlin

override fun onCreate(savedInstanceState: Bundle?) {

super.onCreate(savedInstanceState)

verticalLayout {

padding = dip(30)

editText {

hint = "Name"

textSize = 24f

}

editText {

hint = "Password"

textSize = 24f

}

button("Login") {

textSize = 26f

}

}

}

Page 27: Building android apps with kotlin

There is much more:

▣ kotlinlang.org▣ blog.jetbrains.com/kotlin▣ kotlinlang.org/docs/resources.html▣ Kara- An MVC Framework▣ Android Kotlin Extensions- A collection of Android Kotlin

extensions▣ KAndroid- Kotlin library for Android▣ Anko- Pleasant Android application development

Page 28: Building android apps with kotlin

Thanks!Any questions?

You can find this presentation at: shem8.github.io

[email protected]

Presentation template by SlidesCarnival | Photographs by Unsplash