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

Scala vs Kotlin

Scala vs Kotlin

Talk by Javi Pacheco and Antonio Leiva comparing both languages when developing Android Apps.

Antonio Leiva

December 09, 2015
Tweet

More Decks by Antonio Leiva

Other Decks in Programming

Transcript

  1. SCALA VS KOTLIN
    Javi Pacheco
    @javielinux
    Antonio Leiva
    @lime_cl

    View full-size slide

  2. Introduction

    View full-size slide

  3. • JVM based
    • Functional Language & OOP
    • Immutability emphasis
    • Purity & Effects
    • High-order functions
    • Flexible syntax, create constructs, infix support
    Scala is LOVE

    View full-size slide

  4. Who’s using Scala?

    View full-size slide

  5. 47 Degrees Projects
    Scala Days Scala API Demos Translate Bubble

    View full-size slide

  6. Introduction

    View full-size slide

  7. • JVM based
    • Object-oriented functional language
    • Created by JetBrains (IntelliJ, Android Studio)
    • Simple,lightweight, interoperable

    View full-size slide

  8. • Compiled to Java bytecode
    • Open source
    • Kotlin 1.0 Beta 3

    View full-size slide

  9. Who’s using Kotlin?

    View full-size slide

  10. Who’s using Kotlin?
    BusRadar Omni Reedy Wizbii

    View full-size slide

  11. Hello World!

    View full-size slide

  12. 1. Install plugin

    View full-size slide

  13. 1. Install plugin
    2. Create a Kotlin class

    View full-size slide

  14. 1. Install plugin
    2. Create a Kotlin class
    3. Use “Configure Kotlin in Project”

    View full-size slide

  15. 1. Download SBT and install it
    Installation

    View full-size slide

  16. 1. Download SBT and install it
    2. Install Scala Plugin in IntelliJ
    Installation

    View full-size slide

  17. 1. Download SBT and install it
    2. Install Scala Plugin in IntelliJ
    3. Configure your project
    > sbt
    Installation

    View full-size slide

  18. Null handling

    View full-size slide

  19. val maybeArtist: Option[Artist] = getArtist()

    maybeArtist map { artist =>
    artist.print()
    }
    Some(artist) None
    artist.print() Nothing
    Option Monad

    View full-size slide

  20. val artist: Artist = maybeArtist getOrElse(defaultArtist)
    val maybeArtist: Option[Artist] = Option(getArtist())
    Providing a Default Value
    Java Integration

    View full-size slide

  21. var artist: Artist? = null

    artist.print()
    var artist: Artist? = null

    artist?.print()
    Won’t compile Won’t do anything
    if (artist != null) {

    artist.print()

    }
    Smart cast
    var artist: Artist? = null

    artist!!.print()
    It crashes!

    View full-size slide

  22. UI and Animations

    View full-size slide

  23. verticalLayout {

    val name = editText()

    button("Say Hello") {

    onClick { toast("Hello, ${name.text}!") }

    }

    }
    Anko

    View full-size slide

  24. Kotlin Android Extensions
    Import synthetic properties:
    import kotlinx.android.synthetic.activity_main.*
    Just use them:
    override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)
    setContentView(R.id.main)

    }
    recycler.layoutManager = GridLayoutManager(this, 2)

    recycler.adapter = ContactsAdapter(contacts)


    View full-size slide

  25. • DSL focused to GUI
    • Intensive use of Macros
    • Brings the Functional Programming on Ui
    editText <~ text("foo") <~~ fadeIn <~ enable
    Macroid library
    https://github.com/47deg/functional-views-android

    View full-size slide

  26. Background tasks

    View full-size slide

  27. asyncArtist map { artist =>
    artist.print()
    }
    Future Monad
    val asyncArtist: Future[Artist] = getAsyncArtist
    val asyncFilm: Future[Film] = getAsyncLastFilm(“Barroso”)

    View full-size slide

  28. For Comprehensions
    val asyncFilm = for {
    artist <- getAsyncArtist
    film <- getAsyncLastFilm(artist.name)
    } yield (film)
    asyncFilm map (film => film.print())

    View full-size slide

  29. Anko
    async {

    val contacts = GetContactsCommand().execute(ctx)

    uiThread {

    recycler.adapter = ContactsAdapter(contacts)

    }

    }

    View full-size slide

  30. Kovenant (promises)
    async {

    //some (long running) operation, or just:

    1 + 1

    } then {

    i -> "result: $i"

    } successUi {

    msg -> println(msg)

    }

    View full-size slide

  31. Data persistence

    View full-size slide

  32. var myPref: Long by Preference(this, "name", 0)
    Property delegation
    val prefValue = myPref

    myPref = 20

    View full-size slide

  33. Anko
    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…

    View full-size slide

  34. slick -> http://slick.typesafe.com/
    doobie -> https://github.com/tpolecat/doobie
    Pure functional JDBC layer for Scala
    mvessel -> https://github.com/47deg/mvessel
    JDBC driver written in Scala
    The main goal is to allow the use of ORMs in Android

    View full-size slide

  35. val xa = DriverManagerTransactor[IO](
    "org.postgresql.Driver", "jdbc:postgresql:world", "postgres", ""
    )
    case class Country(code: String, name: String, population: Long)
    def find(n: String): ConnectionIO[Option[Country]] =
    sql"select code, name from country where name = $n”.query[Country].option
    find("France").transact(xa).unsafePerformIO
    Some(Country(FRA, France))
    Doobie Sample

    View full-size slide

  36. Unit Testing
    specs2 -> https://etorreborre.github.io/specs2/
    scalacheck -> https://www.scalacheck.org/

    View full-size slide

  37. JUnit
    Interoperability -> All testing libraries available
    Hamkrest -> https://github.com/npryce/hamkrest
    Mockito-kt -> https://github.com/paslavsky/mockito-kt

    View full-size slide

  38. Multiple inheritance

    View full-size slide

  39. 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

    }

    }

    }

    View full-size slide

  40. Interfaces
    class MainActivity : AppCompatActivity(), ToolbarManager {


    override val toolbar by lazy { find(R.id.toolbar) }


    override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_main)

    initToolbar()

    ...

    }

    }


    View full-size slide

  41. • Fundamental unit of code reuse in Scala
    • A class can mix in any number
    • Order matters
    Traits & self types

    View full-size slide

  42. class MyActivity
    extend Activity
    with PresentationTrait {
    def onCreate() = initUi()
    }
    trait PresentationTrait {
    self: Activity =>
    def initUi() = getApplicationContext
    }
    Example

    View full-size slide

  43. Dependency injection

    View full-size slide

  44. Cake Pattern
    • Dependencies between components
    • Traits & Self types
    macwire -> https://github.com/adamw/macwire
    scaldi -> http://scaldi.org/
    Libraries
    Implicit
    • Dependencies using implicit

    View full-size slide

  45. Simple injection can be done without libraries:
    - Interface delegation
    - Default values for arguments
    Several libraries
    - Dagger 2 (https://github.com/google/dagger)
    - Kodein (https://github.com/SalomonBrys/Kodein)
    - Injekt (https://github.com/kohesive/injekt)

    View full-size slide

  46. Delegate handling

    View full-size slide

  47. val f: (Int, String) -> String = { i, s -> "$s $i" }

    val f = { i: Int, s: String -> "$s $i" }
    fun myFun(listener: (View) -> Unit) {

    ...

    listener(view)

    }
    Variables
    Function parameters

    View full-size slide

  48. Higher-order function
    • Takes one or more functions as arguments
    • Returns a function as its result
    val f1: (Int) => String = (myInt) => myInt.toString
    def myFunc(f: (Int) => String) = {
    println(f(2))
    }

    View full-size slide

  49. Pattern matching

    View full-size slide

  50. def toYesOrNo(choice: Int): String = choice match {
    case 1 => "yes"
    case 0 => "no"
    case _ => "error"
    }
    Traditional approach
    def get(animal: Animal): String = animal match {
    case cat: Cat => “I’m a cat: ” + cat.toString
    case dog: Dog => “I’m a dog: ” + dog.toString
    case _ => “Other animal"
    }
    Typed pattern

    View full-size slide

  51. case class Developer(name: String, lang: String)
    def developer(dev: Developer): String = dev match {
    case Developer(_, “scala”) => “Good Dev"
    case Developer(“Jorge Barroso”, _) => “The best"
    case _ => “Java Developers"
    }
    Cases Classes
    def developer(dev: Developer): String = dev match {
    case Developer(_, “scala”) => “Good Dev"
    case Developer(name, _) if name.contains(“Jorge”) =>
    “The best"
    case _ => “Java Developers"
    }
    If statements

    View full-size slide

  52. No pattern matching, but powerful “when”
    val cost = when(x) {

    in 1..10 -> "cheap"

    in 10..100 -> "regular"

    in 100..1000 -> "expensive"

    in specialValues -> "special value!"

    else -> "not rated"

    }

    View full-size slide

  53. val res = when {

    x in 1..10 -> "cheap"

    s.contains("hello") -> "it's a welcome!"

    v is ViewGroup -> "child count: ${v.getChildCount()}"

    else -> ""

    }

    View full-size slide

  54. Learning curve from
    Java

    View full-size slide

  55. • Really fast -> many similar concepts
    • Interoperability
    • Great official reference and Koans

    View full-size slide

  56. http://scala-exercises.47deg.com/

    View full-size slide

  57. Debugger same as Java
    • Breakpoints
    • Step debugging
    • Watches
    • …
    • All inside Android Studio

    View full-size slide

  58. Debugger same as Java
    • Breakpoints
    • Step debugging
    • Watches
    • …
    • All inside Android Studio

    View full-size slide

  59. Compilation times

    View full-size slide

  60. http://antonioleiva.com/plaid-kotlin-1/

    View full-size slide

  61. • Slower (Scala Compiler + Proguard)
    • Size matters (+ ~2.8 M)
    Compile
    Take your time to setup your SBT
    • Incremental compiler
    • Continuous build and test

    View full-size slide