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

Useful Things You Probably Don't Know About SBT...

Useful Things You Probably Don't Know About SBT, Scala and Play Framework

Mike Slinn covers selected topics from the following ScalaCourses.com courses:

* Introduction to Scala
* Intermediate Scala
* Introduction to Play Framework for Scala
* Wildcard SSL Certificates for Federated Services

Here is the video.

This fast-paced tour through the highlights of four courses covers topics ranging from simple to advanced facts and techniques. Architecture, devops, tools and programming is addressed. The topics are useful and powerful but not well-known, or at least not widely practiced or written about.

Avatar for Mike Slinn

Mike Slinn

March 14, 2016
Tweet

Other Decks in Programming

Transcript

  1. Mike Slinn ScalaCourses.com 2016 Mar 18 Useful Things You Probably

    Don't Know About SBT, Scala, IDEA and Play
  2. GetScala.com • Get a free ScalaCourses.com laptop sticker from GetScala.com

    • We deliver world-wide for free • Tweet a photo of your laptop (with sticker) to @scalacourses
  3. About Mike Slinn • Managing Director, ScalaCourses.com • Tech lead

    for Cadenza (which powers ScalaCourses.com) • Founder, SF Scala Meetup • Former Primary Organizer, Bay Area Scala Enthusiasts (Scala Bay) • Former Chairman, Silicon Valley Ruby Conference • Co-founder, Vancouver AutoCAD Users Society • Expert witness (15 cases to date): distributed systems, e-commerce, intellectual property theft
  4. About ScalaCourses.com • Online Scala and Play training • Self-study

    and instructor-led courses • Courses are packed with practical information so students can start working on real-world projects right away • Each course provides the equivalent of an O’Reilly-sized book, plus videos and access to instructors • 1-year enrollments include all updates to course material • We already have Scala 2.11.8, 2.12 and Play 2.5 and 3 information • Our 4th year of operation
  5. 1) http://scala-lang.org/api/current 2) http://doc.akka.io/docs/akka/current/scala.html 3) http://doc.akka.io/api/akka/current 4) http://scala-sbt.org/0.13/docs 5) https://google.com/advanced_search?as_sitesearch=http://scala-

    sbt.org/0.13/docs Redirects: http://playframework.com/documentation/latest http://playframework.com/documentation/latest/api/scala/index.html Current URLs
  6. • Ctrl-L – manually clear screen • To enable colorized

    Scala REPL: alias scala="scala -Dscala.color=true" • Pasting a transcript Scala 2.11.8 • REPL Here Documents (3 flavors) • Tab completion Scala REPL
  7. • Like Scala REPL, but includes the project on the

    classpath • To enable colorized sbt console, create the following file as ~/.sbt/0.13/repl.sbt: initialize ~= { _ => val ansi = System.getProperty("sbt.log.noformat", "false") != "true" if (ansi) System.setProperty("scala.color", "true") } SBT Console
  8. SBT Tasks • Put in build.sbt to clear screen before

    every compile: triggeredMessage in ThisBuild := Watched.clearWhenTriggered • ~testQuick – incrementally compile modified code and only run test classes that were affected by the change • + task – Perform task for each compiler version in crossScalaVersions $ sbt +compile $ sbt +publish • ++ x.y task – Perform task using version x.y of Scala compiler $ sbt "++2.11.7 compile" $ sbt "++2.11.8 compile"
  9. Examining Dependencies • SBT (and Activator) create XML files showing

    project dependencies whenever they run the update task • Works with all projects, including Play projects $ firefox `find target/resolution-cache/reports/ \ -name \*compile.xml | grep -v javadoc`
  10. External SBT Projects • Working with multiple SBT projects is

    easy to work with if you know how • What’s wrong with SBT sub-projects? • All live in the same git project • All sub-projects must use the same git branch • Merge conflicts maximized • Everyone has equal access to entire code base • Use git subtree to stitch together git projects into one
  11. build.sbt excerpts for 2 sub-projects Project in _model directory: lazy

    val base_model = project.in(file(".")) Dependant project in model directory: lazy val model = Project("model", file(".")) .dependsOn(ProjectRef(uri("../_model"), "base_model"))
  12. Console app: build.sbt lazy val root = (project in file("."))

    .dependsOn( ProjectRef(uri("../_model"), "base_model"), ProjectRef(uri("../model"), "model") )
  13. Play webapp: build.sbt lazy val root = (project in file("."))

    .enablePlugins(PlayScala) .dependsOn( ProjectRef(uri("../_model"), "base_model"), ProjectRef(uri("../model"), "model") )
  14. tmux • Useful for working on servers, where there is

    no GUI • Edit in one console pane, view compiler output in another • Wish there was a standard tmux.conf file • Works best on Mac
  15. IntelliJ IDEA - General • Terminal plugin – run bash,

    git, sbt, etc • Markdown plugin • Regex plugin • Split-pane editing – moving files, resizing • Scroll from Source button – locates current file in project pane • External libraries – expand jars and view source code • Structure Pane – navigation
  16. IntelliJ IDEA – Eclipse Key Bindings • Alt-1 – Toggle

    project pane visibility (twice) • Alt-Home / Alt-Up – use breadcrumbs to navigate • Custom bindings: • Alt-Shift-H,G – View Git History for Selection • Alt-Shift-H,L – View Local History for Selection • Alt-Enter accept suggestions • Ctrl-Space cycle through autocompletions • Ctrl-U evaluate expression • Ctrl-G find usages • Ctrl-Shift-T Search for type • Ctrl+Shift-F12 – Maximize editor
  17. IntelliJ IDEA - Scala • Alt-= – shows current type

    • Disable Scala / Twirl parsing when necessary
  18. Scala Types vs. Classes • A type is is a

    classification that the compiler can verify • A class is a definition that can be instantiated • In Java, List is a raw type • In Scala, List is a class, but not a type (it's actually a higher-kinded type) • List[String] is a type but not a class • Int is a type that does not have an implementing class • Null and Any are types that don't have class instances • The Nothing type doesn't have values or an implementation class • What type is x? val x = if (false) 1.0
  19. • Like methods and functions, and unlike lazy vals, call

    by name parameters are evaluated each time they are referenced • This means they should be assigned to a local variable before use • However, there is no language construct to show they are call by name • IDEs can be configured to show their special status Call by Name Parameters def time[T](block: => T): (Long, T) = { val t0 = System.nanoTime() val result: T = block val elapsedMs = (System.nanoTime() - t0) / 1000000 (elapsedMs, result) }
  20. Import scala.language.implicitConversions package yeller { case class Yeller(s: String) {

    def yell: String = s.toUpperCase + "!!" } object `package` { implicit def stringToYeller(s: String): Yeller = Yeller(s) } } object YellerMain extends App { import yeller._ println("Look out".yell) } What does this program do? • Compare to Implicit Class • How would you rewrite the program so that it is more efficient by using value classes?
  21. scala> case class X[C, D](c: C, d: D) defined class

    X scala> @annotation.implicitAmbiguous("ambig1 problem: X[${J}, ${J}]") implicit def ambig1[J](j: J): X[J, J] = X(j, j) ambig1: [J](j: J)X[J,J] scala> @annotation.implicitAmbiguous("ambig2 problem: X[${J}, ${J}]") implicit def ambig2[J](j: J): X[J, J] = X(j, j) ambig2: [J](j: J)X[J,J] scala> val x12: X[Int, Int] = 1 <console>:15: error: ambig1 problem: X[Int, Int] val x12: X[Int, Int] = 1 ^ Scala 2.12 @implicitAmbiguous
  22. Minimal Play Project build.sbt: lazy val root = (project in

    file(".")).enablePlugins(PlayScala) Project/whatever.sbt: addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.0") That’s it! Nothing to download or install except SBT.
  23. Plain Old Scala View Templates • Twirl should not be

    used to implement a view if: • Part of a response should be cached (in a singleton or in an actual cache) • There are a lot of conditional tests • Looping is nested more than one level • Blocks of code longer than can be displayed on one screen • Multiple variables need to be computed for a block of code • Several templates share code and so would be more maintainable if located in the same file • IDEA does not understand how Scala View Template packages work
  24. include.scala package views.html.helper import java.io.File import play.api.templates.Html import play.api.Play import

    play.api.Play.current import play.api.i18n._ import scala.io.Source.fromFile object include { def apply(filePath: String, rootDir: String = "public")(implicit lang: Lang): Html = { val (fileName, suffix) = filePath.splitAt(filePath.lastIndexOf(".")) val maybeFile = Play.getExistingFile(rootDir + "/" + fileName + "_" + lang.language + suffix). orElse(Play.getExistingFile(rootDir + "/" + filePath)) maybeFile map { file ⇒ val file2 = if (file.isDirectory) new File(file, "index.html") else file val content = fromFile(file2).mkString Html(content) } getOrElse Html("File Not Found") } }
  25. SBT Native Packager • sbt stage and dist tasks do

    not form the basis for a reliable deployment strategy • SBT Native Packager has had significant capability added in the last year • Working with SBT Native Packager requires devops knowledge • I spent 130 hours preparing the ½ hour video • This one lecture is worth the price of the entire course
  26. About the course • Front-ending a Play Framework webapp with

    a web server so static assets are served by the web server provides poor latency and does not scale • Better to use a Content Distribution Network • Many/most CDNs don’t cost much, so go ahead! • Federating cloud infrastructure requires a wildcard SSL certificate • Wildcard SSL certificates are more complex to work with than single-site SSL certificates • Deploying a Play webapp with SSL reliably requires a strong understanding of SBT Native Packager • Follow the instructions and get A+ on the SSL Labs Security assessment • Qualified students should be able to follow the instructions and deploy in one day
  27. More, Better, Faster • “After turning on the java8 backend

    in Scala, our bytecode size decreased by 50% and compile times decreased by 75%.” – Richard Wallace (@purefn) • Use Scala 2.11.8 or 2.12-M3 with these compile options: -Ybackend:GenBCode -Ydelambdafy:method -target:jvm-1.8 • Add this dependency: "org.scala-lang.modules" %% "scala-java8-compat" % "0.7.0" • Not for production (yet)