Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Developing Android with Kotlin

Developing Android with Kotlin

How to develop Android apps using Kotlin language.

Antonio Leiva

April 25, 2015
Tweet

More Decks by Antonio Leiva

Other Decks in Programming

Transcript

  1. What is Kotlin? • JVM based • Object-oriented functional language

    • Created by JetBrains (IntelliJ, Android Studio) • Simple,lightweight, interoperable
  2. 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
  3. Expressive data class Artist(
 var id: Long,
 var name: String,


    var url: String,
 var mbid: String) KOTLIN
  4. 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
  5. 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"
 }
 }
  6. 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
  7. 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
  8. Extension functions fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT){
 Toast.makeText(this,

    message, duration).show()
 } override fun onCreate(savedInstanceState: Bundle?) {
 super<BaseActivity>.onCreate(savedInstanceState)
 toast("This is onCreate!!")
 }
  9. Extension functions inline public fun <reified T : Activity> Activity.navigate(id:

    String) {
 val intent = Intent(this, javaClass<T>())
 intent.putExtra("id", id)
 startActivity(intent)
 } navigate<DetailActivity>("2")
  10. 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)
  11. Default values for arguments inline public fun <reified T :

    Activity> Activity.navigate(
 id: String,
 sharedView: View? = null,
 transitionName: String? = null) {
 
 ...
 } navigate<DetailActivity>("2") navigate<DetailActivity>("2", sharedView, TRANSITION_NAME) navigate<DetailActivity>( id = "2", transitionName = TRANSITION_NAME)
  12. Custom Views • By default, classes only have a unique

    constructor class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) {
 
 init {
 // Initialization code
 }
 }
  13. 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)
 }
 }
  14. 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”
 }
 }
  15. Kotlin Android Extensions Direct access to XML views using its

    id as property name main.xml <FrameLayout
 xmlns:android="..."
 android:id="@+id/frameLayout"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 
 <TextView
 android:id="@+id/welcomeText"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>
 
 </FrameLayout>
  16. Kotlin Android Extensions Import synthetic properties import kotlinx.android.synthetic.main.* Use the

    properties override fun onCreate(savedInstanceState: Bundle?) {
 super<BaseActivity>.onCreate(savedInstanceState) setContentView(R.id.main)
 frameLayout.setVisibility(View.VISIBLE)
 welcomeText.setText("I´m a welcome text!!")
 }
  17. Lambda Expressions Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
 @Override public void onGenerated(Palette

    palette) {
 …
 }
 }); Palette.generateAsync(bitmap) { palette ->
 …
 } JAVA KOTLIN
  18. Lambda Expressions view.setOnClickListener({
 toast("Click")
 }) If trait (interface) only has

    a function, substitute by function view.setOnClickListener({ view ->
 toast("Click")
 })
  19. Lambda Expressions view.setOnClickListener(){
 toast("Click")
 } If last parameter is a

    function, can go out of parenthesis view.setOnClickListener{
 toast("Click")
 }
  20. Extending language ‘With’ function fun <T> with(t: T, body: T.()

    -> Unit) { t.body() } with(titleText) {
 setPivotX(0f)
 setPivotY(getHeight().toFloat())
 updateTitleScale(this, minHeight, maxHeight, 0)
 }
  21. 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)
 }
  22. 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
  23. 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
 }
 }
  24. 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<ActionBarActivity>.onCreate(savedInstanceState)
 initDrawer()
 initHeader()
 initSearch()
 }
 }
  25. Collections Operations // Inmutable
 val list = listOf(1, 2, 3,

    4, 5)
 
 // Mutable
 val mutableList = ArrayList<Int>()
 mutableList[0] = 1
 val first = mutableList[0]
 
 // Map
 val map = HashMap<String, Int>()
 map["key"] = 1
 val value = map["key"]
  26. 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
  27. 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
  28. Production ready? • Stable enough • Not final: 1.0 ->

    Summer 2015 • Language definition still changing
  29. 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