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

Android with Kotlin

Android with Kotlin

Slides from my talk Android with Kotlin at Oct 2017 GDG 6 October City, Egypt.

Ahmed Tarek

October 12, 2017
Tweet

Other Decks in Programming

Transcript

  1. Kotlin • By JetBrains in 2011 • Open sourced in

    2012 • The first officially stable release in 2016
  2. Kotlin • Statically typed programming language • 100% interoperable with

    Java and Android • Avoid entire classes of errors such as null pointer exceptions.
  3. var / val var name = "Ahmed" val id =

    1 Val cannot be reassigned id = 3
  4. Null Safety Safe var name: String name = null //

    Compilation error Nullable val name: String? = null // Nullable type println(name.length()) // Compilation error println(name?.length())
  5. Data Class data class Car( var name: String, var color:

    Int, var speed: Float) • No need to implement: toString, equals
  6. Companion Object class Car { companion object { fun drive()

    { } } } // Like calling a static method Car.drive()
  7. Simple Android Activity class MainActivity : Activity() { override fun

    onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val name = savedInstanceState?.getString("name") } }
  8. Extending Language isLollipop { view.elevation = 3.0f } . .

    . . inline fun isLollipop(code: () -> Unit) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { code.invoke() } }
  9. Smart Cast fun setData(view: View) { if (view is ImageView)

    { view.setImageDrawable(drawable) } if (view is TextView) { view.setText("hello") } }
  10. Callback/Lambda • view.setOnClickListener(object : View.OnClickListener { override fun onClick(view: View?)

    { doSomething() } }) • view.setOnClickListener { view -> doSomething(view) } • view.setOnClickListener { doSomething() }
  11. Function Parameter Default Value fun toast(message: String) { Toast.toast(this, message,

    Toast.LENGTH_LONG).show() } fun toast(message: String, duration: Int) { Toast.makeText(this, message, duration).show() } fun toast(message: String, duration: Int = Toast.LENGTH_LONG) { Toast.makeText(this, message, duration).show() }
  12. Extension Functions fun Activity.toast(message: String, duration: Int = Toast.LENGTH_LONG) {

    Toast.makeText(this, message, duration).show() } // Call it from any activity instance toast("Hello World!") toast("Hello World!", Toast.LENGTH_SHORT)
  13. Kotlin Android Extensions import kotlinx.android.synthetic.main.activity_main.* override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) photo.setImageBitmap(bitmap) name.setText("Hello World!") }