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. • JVM based • Functional Language & OOP • Immutability

    emphasis • Purity & Effects • High-order functions • Flexible syntax, create constructs, infix support Scala is LOVE
  2. • JVM based • Object-oriented functional language • Created by

    JetBrains (IntelliJ, Android Studio) • Simple,lightweight, interoperable
  3. 1. Install plugin 2. Create a Kotlin class 3. Use

    “Configure Kotlin in Project”
  4. 1. Download SBT and install it 2. Install Scala Plugin

    in IntelliJ 3. Configure your project > sbt Installation
  5. val maybeArtist: Option[Artist] = getArtist()
 maybeArtist map { artist =>

    artist.print() } Some(artist) None artist.print() Nothing Option Monad
  6. val artist: Artist = maybeArtist getOrElse(defaultArtist) val maybeArtist: Option[Artist] =

    Option(getArtist()) Providing a Default Value Java Integration
  7. 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!
  8. Kotlin Android Extensions Import synthetic properties: import kotlinx.android.synthetic.activity_main.* Just use

    them: override fun onCreate(savedInstanceState: Bundle?) {
 super<BaseActivity>.onCreate(savedInstanceState) setContentView(R.id.main)
 } recycler.layoutManager = GridLayoutManager(this, 2)
 recycler.adapter = ContactsAdapter(contacts)

  9. • 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
  10. asyncArtist map { artist => artist.print() } Future Monad val

    asyncArtist: Future[Artist] = getAsyncArtist val asyncFilm: Future[Film] = getAsyncLastFilm(“Barroso”)
  11. For Comprehensions val asyncFilm = for { artist <- getAsyncArtist

    film <- getAsyncLastFilm(artist.name) } yield (film) asyncFilm map (film => film.print())
  12. Kovenant (promises) async {
 //some (long running) operation, or just:


    1 + 1
 } then {
 i -> "result: $i"
 } successUi {
 msg -> println(msg)
 }
  13. 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…
  14. 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
  15. 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
  16. 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
 }
 }
 }
  17. 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()
 ...
 }
 }

  18. • Fundamental unit of code reuse in Scala • A

    class can mix in any number • Order matters Traits & self types
  19. class MyActivity extend Activity with PresentationTrait { def onCreate() =

    initUi() } trait PresentationTrait { self: Activity => def initUi() = getApplicationContext } Example
  20. Cake Pattern • Dependencies between components • Traits & Self

    types macwire -> https://github.com/adamw/macwire scaldi -> http://scaldi.org/ Libraries Implicit • Dependencies using implicit
  21. 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)
  22. 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
  23. 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)) }
  24. 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
  25. 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
  26. 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"
 }
  27. val res = when {
 x in 1..10 -> "cheap"


    s.contains("hello") -> "it's a welcome!"
 v is ViewGroup -> "child count: ${v.getChildCount()}"
 else -> ""
 }
  28. Debugger same as Java • Breakpoints • Step debugging •

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

    Watches • … • All inside Android Studio
  30. • Slower (Scala Compiler + Proguard) • Size matters (+

    ~2.8 M) Compile Take your time to setup your SBT • Incremental compiler • Continuous build and test