Building android apps with kotlin

Post on 09-Apr-2017

221 views 2 download

Transcript of Building android apps with kotlin

Developing Android apps

with KotlinAVGeeks, June 2016

Shem Magnezi

Shem Magnezi@shemag8 | shem8.github.com

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.

Yes but...

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

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.

Kotlin

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

100% interoperable with Java™

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).

Code!

1.Basic syntax

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 })

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)

}

2.Null Safety

‘’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

var a: String = "abc"

a = null // compilation error

var b: String? = "abc"

b = null // ok

val l = b?.length ?: -1

3.Data Classes

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()

4.Extensions

Functions

fun Date.isThuesday() Boolean {

return day == 2

}

if (date.isTuesday) {

...

}

fun Date.isThuesday() = day == 2

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

beginTransaction()

try {

func()

setTransactionSuccessful()

} finally {

endTransaction()

}

}

db.inTransaction {

}

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()

}

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")

}

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)

}

5.Android

Extensions

// 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

}

}

6.Anko library

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

}

}

}

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

Thanks!Any questions?

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

smagnezi8@gmail.com

Presentation template by SlidesCarnival | Photographs by Unsplash