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

Kotlin for Android Developers

Kotlin for Android Developers

Discover some of the most interesting Kotlin features that will make Android development much easier.

Slides from talk at CodeWeek Cáceres (October 2015)

Antonio Leiva

October 17, 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. Null safety 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
  3. Properties private String field = “”;
 
 public String getField()

    {
 return field;
 }
 
 public void setField(String field) {
 this.field = field;
 } JAVA
  4. Properties var property: String = ""
 get(){
 return "property is

    $field"
 }
 set(value: String){
 if (value != "")
 field = value
 }
  5. Data Classes 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
  6. Data Classes data class Artist(
 var id: Long,
 var name:

    String,
 var url: String,
 var mbid: String) KOTLIN
  7. Lambdas public interface Callback<T> {
 void invoke(T result);
 }
 


    public void asyncOperation(int value, Callback<Boolean> callback){
 ...
 callback.invoke(true);
 } JAVA asyncOperation(5, new Callback<Boolean>() {
 @Override public void invoke(Boolean result) {
 System.out.println("Result: " + result);
 }
 });
  8. Lambdas fun asyncOperation(value: Int, callback: (Boolean) -> Unit) {
 ...


    callback(true)
 } asyncOperation(5) { result ->
 println("result: $result")
 }
  9. Lambdas fun asyncOperation(value: Int, callback: (Boolean) -> Unit) {
 ...


    callback(true)
 } asyncOperation(5) { result ->
 println("result: $result")
 } asyncOperation(5) { println("result: $it") }
  10. Lambdas asyncOperation(5) { println("result: $it") } asyncOperation(5, new Callback<Boolean>() {


    @Override public void invoke(Boolean result) {
 System.out.println("Result: " + result);
 }
 });
  11. Collections • Iterable • Collection • List • Set •

    Map filter sort map zip dropWhile first firstOrNull last lastOrNull fold …
  12. Collections parsedContacts .filter { it.name != null && it.image !=

    null }
 .sortedBy { it.name }
 .map { Contact(it.id, it.name!!, it.image!!) }
  13. Extending language inline fun supportsLollipop(code:() -> Unit) {
 if (Build.VERSION.SDK_INT

    >= Build.VERSION_CODES.LOLLIPOP){
 code.invoke()
 }
 } supportsLollipop {
 getWindow().setStatusBarColor(Color.BLACK)
 }
  14. Extension functions fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
 val

    df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
 return df.format(this)
 }
  15. Default arguments fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
 val

    df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
 return df.format(this)
 }
  16. Default arguments fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
 val

    df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
 return df.format(this)
 } dateLong.toDateString()
 dateLong.toDateString(DateFormat.FULL)
  17. Default 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)
  18. Interfaces • Can contain code (but not state) interface ToolbarManager

    {
 
 val toolbar: Toolbar
 
 fun initToolbar() {
 toolbar.inflateMenu(R.menu.menu_main)
 toolbar.setOnMenuItemClickListener {
 when (it.itemId) {
 R.id.action_settings -> App.instance.toast("Settings")
 else -> App.instance.toast("Unknown option")
 }
 true
 }
 }
 }
  19. Interfaces class MainActivity : AppCompatActivity(), ToolbarManager {
 
 override val

    toolbar by lazy { find<Toolbar>(R.id.toolbar) }
 
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 initToolbar()
 ...
 }
 }

  20. Property delegation val toolbar by lazy { find<Toolbar>(R.id.toolbar) } •

    Lazy var p by Delegates.observable("") { d, old, new -> db.saveChanges(this, new) } • Observable • Not Null • Vetoable • Values from map • Custom
  21. Flow control • When val cost = when(x) {
 in

    1..10 -> "cheap"
 in 10..100 -> "regular"
 in 100..1000 -> "expensive"
 in specialValues -> "special value!"
 else -> "not rated"
 }
  22. Flow control • When val res = when {
 x

    in 1..10 -> "cheap"
 s.contains("hello") -> "it's a welcome!"
 v is ViewGroup -> "child count: ${v.getChildCount()}"
 else -> ""
 }
  23. Interoperability If interface only has a function, substitute by function

    view.setOnClickListener({ view ->
 toast("Click")
 })
  24. Interoperability view.setOnClickListener({
 toast("Click")
 }) If interface only has a function,

    substitute by function view.setOnClickListener({ view ->
 toast("Click")
 })
  25. Interoperability view.setOnClickListener() {
 toast("Click")
 } If last parameter is a

    function, can go out of parenthesis view.setOnClickListener {
 toast("Click")
 }
  26. 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>
  27. 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!!")
 }
  28. UI declaration DSL verticalLayout {
 val name = editText()
 button("Say

    Hello") {
 onClick { toast("Hello, ${name.text}!") }
 }
 }
  29. Useful extensions startActivity<DetailActivity>("id" to res.id, "name" to res.name) Start an

    activity Access to system services context.layoutInflater context.notificationManager
 context.sensorManager
 context.vibrator
  30. Useful extensions Toasts and Alert dialogs toast(R.string.message)
 longToast("Wow, such a

    duration")
 
 alert("Yes /no Alert") {
 positiveButton("Yes") { submit() }
 negativeButton("No") {}
 }.show()
  31. SQLite helpers ManagedSQLiteOpenHelper dbHelper.use {
 select("TABLE_NAME").where("_id = {id}", "id" to

    20)
 } db.createTable("TABLE_NAME", true,
 "_id" to INTEGER + PRIMARY_KEY,
 "name" to TEXT) parseList / parseOpt / classParser…
  32. http://antonioleiva.com/book/ Kotlin for Android Developers • Create App from scratch

    • Step by step • Complete Kotlin coverage • Updated to latest version