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 Slide

  2. Introduction

    View Slide

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

    View Slide

  4. Who’s using Scala?

    View Slide

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

    View Slide

  6. Introduction

    View Slide

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

    View Slide

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

    View Slide

  9. Who’s using Kotlin?

    View Slide

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

    View Slide

  11. Hello World!

    View Slide

  12. 1. Install plugin

    View Slide

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

    View Slide

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

    View Slide

  15. View Slide

  16. 1. Download SBT and install it
    Installation

    View Slide

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

    View Slide

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

    View Slide

  19. Null handling

    View Slide

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

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

    View Slide

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

    View Slide

  22. 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 Slide

  23. UI and Animations

    View Slide

  24. verticalLayout {

    val name = editText()

    button("Say Hello") {

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

    }

    }
    Anko

    View Slide

  25. 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 Slide

  26. • 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 Slide

  27. Background tasks

    View Slide

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

    View Slide

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

    View Slide

  30. Anko
    async {

    val contacts = GetContactsCommand().execute(ctx)

    uiThread {

    recycler.adapter = ContactsAdapter(contacts)

    }

    }

    View Slide

  31. Kovenant (promises)
    async {

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

    1 + 1

    } then {

    i -> "result: $i"

    } successUi {

    msg -> println(msg)

    }

    View Slide

  32. Data persistence

    View Slide

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

    myPref = 20

    View Slide

  34. 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 Slide

  35. 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 Slide

  36. 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 Slide

  37. Testing

    View Slide

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

    View Slide

  39. View Slide

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

    View Slide

  41. Spek

    View Slide

  42. Multiple inheritance

    View Slide

  43. 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 Slide

  44. 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 Slide

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

    View Slide

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

    View Slide

  47. Dependency injection

    View Slide

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

    View Slide

  49. 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 Slide

  50. Delegate handling

    View Slide

  51. 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 Slide

  52. 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 Slide

  53. Pattern matching

    View Slide

  54. 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 Slide

  55. 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 Slide

  56. 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 Slide

  57. val res = when {

    x in 1..10 -> "cheap"

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

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

    else -> ""

    }

    View Slide

  58. Learning curve from
    Java

    View Slide

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

    View Slide

  60. View Slide

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

    View Slide

  62. Debugger

    View Slide

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

    View Slide

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

    View Slide

  65. Compilation times

    View Slide

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

    View Slide

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

    View Slide