Slide 1

Slide 1 text

Developing Android with Kotlin

Slide 2

Slide 2 text

Antonio Leiva Android Engineer @ Plex, Inc http://antonioleiva.com http://plus.google.com/+AntonioLeivaGordillo @lime_cl

Slide 3

Slide 3 text

http://plex.tv

Slide 4

Slide 4 text

Bandhook Kotlin http://github.com/antoniolg/Bandhook-Kotlin

Slide 5

Slide 5 text

Index 1. What is Kotlin? 2. Configure your project 3. Kotlin on Android 4. Conclusions

Slide 6

Slide 6 text

What is Kotlin? 1. Introduction 2. Expressive 3. Type safe 4. Functional

Slide 7

Slide 7 text

What is Kotlin? • JVM based • Object-oriented functional language • Created by JetBrains (IntelliJ, Android Studio) • Simple,lightweight, interoperable

Slide 8

Slide 8 text

Expressive public class Artist {
 private long id;
 private String name;
 private String url;
 private String mbid;
 
 public long getId() {
 return id;
 }
 
 public void setId(long id) {
 this.id = id;
 }
 
 public String getName() {
 return name;
 }
 
 public void setName(String name) {
 this.name = name;
 }
 
 public String getUrl() {
 return url;
 }
 
 public void setUrl(String url) {
 this.url = url;
 }
 
 public String getMbid() {
 return mbid;
 }
 
 public void setMbid(String mbid) {
 this.mbid = mbid;
 }
 
 @Override public String toString() {
 return "Artist{" +
 "id=" + id +
 ", name='" + name + '\'' +
 ", url='" + url + '\'' +
 ", mbid='" + mbid + '\'' +
 '}';
 }
 }
 JAVA

Slide 9

Slide 9 text

Expressive data class Artist(
 var id: Long,
 var name: String,
 var url: String,
 var mbid: String) KOTLIN

Slide 10

Slide 10 text

Type safe Artist artist = null;
 artist.print(); JAVA Null Pointer Exception

Slide 11

Slide 11 text

Type safe KOTLIN var artist: Artist? = null
 artist.print() var artist: Artist? = null
 artist?.print() won´t compile will do nothing if (artist != null) {
 artist.print()
 } Smart cast var artist: Artist? = null
 artist!!.print() will crash

Slide 12

Slide 12 text

Functional • Functional support (lambdas) view.setOnClickListener { toast("Hello world!") }

Slide 13

Slide 13 text

Configure your project 1. Kotlin plugin install and configuration 2. Build.grade tweaks 3. Code transformation

Slide 14

Slide 14 text

Configure your project 1. Create a new Android Project

Slide 15

Slide 15 text

Configure your project 2. Download Kotlin plugin for Android Studio

Slide 16

Slide 16 text

Configure your project 3. Create new Kotlin folder

Slide 17

Slide 17 text

Configure your project 4. Parent build.grade buildscript {
 ext.kotlin_version = "0.11.91"
 repositories {
 jcenter()
 }
 dependencies {
 classpath "com.android.tools.build:gradle:1.1.3"
 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
 }
 }

Slide 18

Slide 18 text

Configure your project 5. App build.grade apply plugin: 'com.android.application'
 apply plugin: 'kotlin-android' Apply plugin dependencies {
 compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
 } Kotlin library dependency android {
 …
 sourceSets {
 main.java.srcDirs += 'src/main/kotlin'
 }
 } Add kotlin folder to srcDirs

Slide 19

Slide 19 text

Configure your project 4b. Modify build.gradle files (alternative)

Slide 20

Slide 20 text

Configure your project 5. Transform main activity to kotlin code

Slide 21

Slide 21 text

Configure your project 5. Transform main activity to kotlin code

Slide 22

Slide 22 text

Kotlin on Android 1. Extension functions 2. Default values for arguments 3. Custom Views 4. Kotlin Android Extensions 5. Lambda Expressions 6. Extending language 7. Partial mult-inheritance 8. Collections

Slide 23

Slide 23 text

Extension functions fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
 Toast.makeText(this, message, duration).show()
 } override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 toast("This is onCreate!!")
 }

Slide 24

Slide 24 text

Extension functions inline public fun Activity.navigate(id: String) {
 val intent = Intent(this, javaClass())
 intent.putExtra("id", id)
 startActivity(intent)
 } navigate("2")

Slide 25

Slide 25 text

Default values for arguments fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
 Toast.makeText(this, message, duration).show()
 } toast(“Short Toast!!”) toast("Long Toast!!", Toast.LENGTH_LONG)

Slide 26

Slide 26 text

Default values for arguments inline public fun Activity.navigate(
 id: String,
 sharedView: View? = null,
 transitionName: String? = null) {
 
 ...
 } navigate("2") navigate("2", sharedView, TRANSITION_NAME) navigate( id = "2", transitionName = TRANSITION_NAME)

Slide 27

Slide 27 text

Custom Views • By default, classes only have a unique constructor class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) {
 
 init {
 // Initialization code
 }
 }

Slide 28

Slide 28 text

Custom Views • Since Kotlin M11, multiple constructors class SquareImageView : ImageView {
 
 public constructor(context: Context) : super(context) {
 }
 
 public constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
 }
 
 public constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
 }
 
 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
 super.onMeasure(widthMeasureSpec, heightMeasureSpec)
 val width = getMeasuredWidth()
 setMeasuredDimension(width, width)
 }
 }

Slide 29

Slide 29 text

Kotlin Android Extensions • A extension of Kotlin library for Android apps • Currently includes a view binder • A new plugin buildscript {
 …
 dependencies { …
 classpath “org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version”
 }
 }

Slide 30

Slide 30 text

Kotlin Android Extensions Direct access to XML views using its id as property name main.xml 
 
 
 


Slide 31

Slide 31 text

Kotlin Android Extensions Import synthetic properties import kotlinx.android.synthetic.main.* Use the properties override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState) setContentView(R.id.main)
 frameLayout.setVisibility(View.VISIBLE)
 welcomeText.setText("I´m a welcome text!!")
 }

Slide 32

Slide 32 text

Lambda Expressions Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
 @Override public void onGenerated(Palette palette) {
 …
 }
 }); Palette.generateAsync(bitmap) { palette ->
 …
 } JAVA KOTLIN

Slide 33

Slide 33 text

Lambda Expressions view.setOnClickListener(object : View.OnClickListener{
 override fun onClick(v: View) {
 toast("Click")
 }
 }) Regular anonymous class (similar to Java)

Slide 34

Slide 34 text

Lambda Expressions view.setOnClickListener({
 toast("Click")
 }) If trait (interface) only has a function, substitute by function view.setOnClickListener({ view ->
 toast("Click")
 })

Slide 35

Slide 35 text

Lambda Expressions view.setOnClickListener(){
 toast("Click")
 } If last parameter is a function, can go out of parenthesis view.setOnClickListener{
 toast("Click")
 }

Slide 36

Slide 36 text

Lambda Expressions view.setOnClickListener(object : View.OnClickListener{
 override fun onClick(v: View) {
 toast("Click")
 }
 }) view.setOnClickListener { toast("Click") }

Slide 37

Slide 37 text

Extending language ‘With’ function fun with(t: T, body: T.() -> Unit) { t.body() } with(titleText) {
 setPivotX(0f)
 setPivotY(getHeight().toFloat())
 updateTitleScale(this, minHeight, maxHeight, 0)
 }

Slide 38

Slide 38 text

Extending language Check Android version inline fun supportsLollipop(code:() -> Unit){
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
 code.invoke()
 }
 } supportsLollipop {
 getWindow().setStatusBarColor(Color.BLACK)
 }

Slide 39

Slide 39 text

Partial multi-inheritance Inheritance through Traits • Most similar thing to Interfaces in Java • Can contain code • Can´t contain state • Can declare properties • Properties are abstract for children • A class can extend several traits • A trait can extend another class • Can use parent functions • Can´t call ‘super’ on overriden functions

Slide 40

Slide 40 text

Partial multi-inheritance trait NavigationActivity : ActionBarActivity {
 val navigationDrawer: DrawerLayout
 fun initDrawer() { "..." }
 }
 
 trait SearchActivity : ActionBarActivity {
 var searchView: SearchView
 fun initSearch() { "..." }
 }
 
 trait ScrollHeaderActivity : ActionBarActivity {
 fun initHeader(){
 val image = findViewById(R.id.image) as ImageView
 val title = findViewById(R.id.title) as TextView
 }
 }

Slide 41

Slide 41 text

Partial multi-inheritance class MyActivity : ActionBarActivity(), NavigationActivity,
 SearchActivity, ScrollHeaderActivity {
 
 override val navigationDrawer: DrawerLayout by bindView(R.id.drawer)
 override var searchView: SearchView by Delegates.notNull()
 
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 initDrawer()
 initHeader()
 initSearch()
 }
 }

Slide 42

Slide 42 text

Collections Operations filter sort map zip dropWhile first firstOrNull last lastOrNull fold …

Slide 43

Slide 43 text

Collections Operations fun transform(artists: List): List {
 return artists filter { isValid(it) } map { transform(it) }
 }

Slide 44

Slide 44 text

Collections Operations // Inmutable
 val list = listOf(1, 2, 3, 4, 5)
 
 // Mutable
 val mutableList = ArrayList()
 mutableList[0] = 1
 val first = mutableList[0]
 
 // Map
 val map = HashMap()
 map["key"] = 1
 val value = map["key"]

Slide 45

Slide 45 text

Conclusions • Kotlin in numbers • Limitations • Production ready?

Slide 46

Slide 46 text

Kotlin in numbers Library Jar Size Dex Size Method Count Field Count kotlin-runtime-0.10.195 354 KB 282 KB 1071 391 kotlin-stdlib-0.10.195 541 KB 835 KB 5508 458 play-services- base-6.5.87 773 KB 994 KB 5212 2252 support-v4-21.0.3 745 KB 688 KB 6721 1886 Using project Kotlin in Android (Jake Wharton): http://goo.gl/ZFtbBw

Slide 47

Slide 47 text

Limitations • Customs Views (Available since M11) • Interoperability with auto generated code • Many libraries use $ for auto generated names • Not possible to use Dagger 1 or Butterknife • jUnit testing in Android projects

Slide 48

Slide 48 text

Production ready? • Stable enough • Not final: 1.0 -> Summer 2015 • Language definition still changing

Slide 49

Slide 49 text

Bibliography • Kotlin reference
 http://kotlinlang.org • Kotlin official blog
 http://blog.jetbrains.com/kotlin/ • Kotlin: The swift of Android
 https://www.youtube.com/watch?v=dJscNr1silY • Using project Kotlin in Android
 http://goo.gl/ZFtbBw


Slide 50

Slide 50 text

Questions? http://antonioleiva.com http://plus.google.com/+AntonioLeivaGordillo @lime_cl