Share
Embed
Developing Android with Kotlin
How to develop Android apps using Kotlin language.
Antonio Leiva
April 25, 2015
Transcript
50 slides
-
Index 1. What is Kotlin? 2. Configure your project 3.
Kotlin on Android 4. Conclusions -
What is Kotlin? • JVM based • Object-oriented functional language
• Created by JetBrains (IntelliJ, Android Studio) • Simple,lightweight, interoperable -
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 -
Expressive data class Artist( var id: Long, var name: String,
var url: String, var mbid: String) KOTLIN -
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 -
Configure your project 1. Kotlin plugin install and configuration 2.
Build.grade tweaks 3. Code transformation -
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" } } -
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 -
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 -
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!!") } -
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") -
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) -
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) -
Custom Views • By default, classes only have a unique
constructor class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) { init { // Initialization code } } -
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) } } -
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” } } -
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> -
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!!") } -
Lambda Expressions Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette
palette) { … } }); Palette.generateAsync(bitmap) { palette -> … } JAVA KOTLIN -
Lambda Expressions view.setOnClickListener(object : View.OnClickListener{ override fun onClick(v: View) {
toast("Click") } }) Regular anonymous class (similar to Java) -
Lambda Expressions view.setOnClickListener({ toast("Click") }) If trait (interface) only has
a function, substitute by function view.setOnClickListener({ view -> toast("Click") }) -
Lambda Expressions view.setOnClickListener(){ toast("Click") } If last parameter is a
function, can go out of parenthesis view.setOnClickListener{ toast("Click") } -
Lambda Expressions view.setOnClickListener(object : View.OnClickListener{ override fun onClick(v: View) {
toast("Click") } }) view.setOnClickListener { toast("Click") } -
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) } -
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) } -
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 -
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 } } -
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() } } -
Collections Operations filter sort map zip dropWhile first firstOrNull last
lastOrNull fold … -
Collections Operations fun transform(artists: List<LastFmArtist>): List<Artist> { return artists filter
{ isValid(it) } map { transform(it) } } -
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"] -
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 -
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 -
Production ready? • Stable enough • Not final: 1.0 ->
Summer 2015 • Language definition still changing -
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