SlideShare a Scribd company logo
1 of 18
Download to read offline
Intro to Scala.js
Marius Soutier
Freelance Software Engineer
@mariussoutier
Write JavaScript in Scala
What is Scala.js?
Scala.js compiles Scala to JavaScript
object HelloUg extends JSApp {

override def main(): Unit = {

// FP for the win

var res, i = 0

val values = js.Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

while (i < values.length) {

res = res + values(i)

i += 1

}

println(res)

}

}
$c_Lug_HelloUg$.prototype.main__V = (function() {

var res = 0;

var i = 0;

var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

while ((i < $uI(values["length"]))) {

res = ((res + $uI(values[i])) | 0);

i = ((1 + i) | 0)

};

var x = res;

var this$2 = $m_s_Console$();

var this$3 = this$2.outVar$2;

$as_Ljava_io_PrintStream(this$3.tl$1.get__O()).println__O__V(x)

});
$e["ug"] = ($e["ug"] || {});
$e["ug"]["HelloUg"] = $m_Lug_HelloUg$;
But Why?
• Web development is moving to client-side apps,

JavaScript is the browser’s only language
• JavaScript is beyond broken
• Maintaining a large JavaScript project can be difficult
• Keeping up with JavaScript’s ecosystem is nigh-
impossible

(See JavaScript Drinking Game)
Obligatory JavaScript: The Good Parts
Reference
But that’s enough JavaScript bashing for today
Scala.js to the Rescue
• We all love Scala
• Type-safety, packages, traits, …
• Rich standard library
• Share code between backend and front-end
• Full editor support (same file suffix)
• Access to all JS libs and a lot of the Scala ecosystem
Scala.js’ Future
• Size of compiled JavaScript
• Compile Speed
• JS libraries must be wrapped
• Scala is developed with JVM in mind, some things
just don't work in JS land, some JDK parts missing
• Front-end developers might not want to learn Scala
(slackers!)
Drawbacks
• Scala libraries available for Scala.js
• Scalatags, ScalaCSS
• Shapeless, Scalaz, Cats, Monocle
• Sharing code inside a project via common cross-compiled

sbt sub-project
• Data exchange via JSON
• upickle
• JavaScript doesn't necessarily understand your JSON, 

e.g. Longs aren't that long in JavaScript
Sharing Code & Data
How Does It Work?
.scala
.class
.sjsir
run/test
~fastOptJS
fullOptJS
Google
Closure
-opt.js
-fastopt.js
Rhino / Node.js
Rhino / PhantomJS
No DOM
DOM
-jsdeps.min.js
jsDependencies ++= Seq(

"org.webjars" % "jquery" % "1.10.2" / "jquery.js",

"org.webjars" % "angularjs" % "1.4.8" / "angular.js" dependsOn "jquery.js"

)
Targeting JavaScript
Scala / JVM JavaScript
Byte, Short, Int, Float, Double Number
Unit Undefined
Char, Long Scala classes
Custom Scala classes JavaScript class with @JSExport
NullPointerException,
ArrayIndexOutOfBoundsException,
ClassCastException, StackOverflowError, …
Undefined
Reflection -
String.split JS RegEx is different
Pattern Matching on Byte, Short, Int, Float, Double Determined by runtime value, not type
JavaScript Native Types
JS-native Type Maps to Example JS
js.FunctionN scala.FunctioN val fn: js.Function1[Int, Int] =
(i: Int) => i * 2
var fn = function(i)
{

return i * 2;

};
js.Array[T] Seq[T] js.Array(1, 2, 3) [1, 2, 3]
js.Dictionary[T] mutable.Map[String, T] js.Dictionary("a" -> 1, "b" -> 2) {"a": 1, "b": 2}
js.UndefOr[T] Option[T]
val some: js.UndefOr[Int] = 1

val none: js.UndefOr[Int] =
js.undefined

Option(1).orUndefined
1

undefined


1
js.TupleN TupleN js.Tuple2(42, “Scala UG") [42, "Scala UG"]
Dynamic JS
When interacting with JavaScript libraries, its dynamic

nature can’t always be ignored
val guest = js.Dynamic.literal(

name = "Scala User Group"

)
But we can give it a nicer interface
trait Guest extends js.Object {

val name: String = js.native

}



object Guest {

def apply(name: String): Guest =

js.Dynamic.literal(name = name).asInstanceOf[Guest]

}
import js.Dynamic.{global => g}

g.console.log(guest)



val dom = g.document

val p = dom.createElement("p")

p.innerHTML = s"Hi ${guest.name}!"

dom.getElementById("main").appendChild(p)
Wrapping JS Libs (1)
Read documentation and infer types
Wrapping JS Libs (2)
import scala.scalajs.js

import scala.scalajs.js.annotation.JSName



object Numeral {

def apply(n: Double): Numeral = new Numeral(n)

def apply(): Numeral = new Numeral(0)

}



@JSName("numeral")

@js.native

class Numeral(n: Double) extends js.Object {

def format(formatString: String): String = js.native

def unformat(formatString: String): Double = js.native



def add(number: Double): Double = js.native

def subtract(number: Double): Double = js.native

def multiply(number: Double): Double = js.native

def divide(number: Double): Double = js.native



def value(): Double = js.native



def difference(number: Double): Double = js.native

}
jsDependencies ++= Seq(

"org.webjars" % "numeral-js" % "1.5.3-1" / "numeral.js" minified "min/numeral.min.js"

)
Numeral(totalValue).format("0,0.00")
Manipulating the DOM
libraryDependencies ++= Seq(

"org.scala-js" %%% "scalajs-dom" % "0.8.2"

)
import org.scalajs.dom._

val main = document.getElementById("main")

val p = document.createElement("p")

val text = document.createTextNode("Hi Scala User Group!")

p.appendChild(text)

main.appendChild(p)
AJAX
import org.scalajs.dom.ext.Ajax
import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue


val eventualUsers =

Ajax

.get(url = "/users/")

.map { xmlHttp =>

xmlHttp.status match {

case 200 =>

import upickle.default._

read[Seq[User]](xmlHttp.responseText)

case other =>

Seq.empty[User]

}

}
• Export classes to JS for use from other JS code
• Can even publish as NPM module
Using Scala.js from JS
@JSExport

case class ExportedUser(

@(JSExport@field) name: String,

@(JSExport@field) email: String

)
@JSExport

@ScalaJSDefined

class Foo extends js.Object {

val x: Int = 4

def bar(x: Int): Int = x + 1

}
Questions?

More Related Content

What's hot

Django Multi-DB in Anger
Django Multi-DB in AngerDjango Multi-DB in Anger
Django Multi-DB in AngerLoren Davie
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotionStefan Haflidason
 
Using JavaScript in Drupal
Using JavaScript in DrupalUsing JavaScript in Drupal
Using JavaScript in Drupalkatbailey
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laidSwizec Teller
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkChris Westin
 
Workload Replay in the Cloud: Secret Weapon for Cloud Migrations
Workload Replay in the Cloud: Secret Weapon for Cloud MigrationsWorkload Replay in the Cloud: Secret Weapon for Cloud Migrations
Workload Replay in the Cloud: Secret Weapon for Cloud MigrationsJohn Sterrett
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...Codemotion
 
Mssql to mysql - Anton Ivanov
Mssql to mysql - Anton IvanovMssql to mysql - Anton Ivanov
Mssql to mysql - Anton IvanovDrupalCamp Kyiv
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Andy Bunce
 
SQL and NoSQL Better Together in Alasql
SQL and NoSQL Better Together in AlasqlSQL and NoSQL Better Together in Alasql
SQL and NoSQL Better Together in AlasqlAndrey Gershun
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAndrey Gershun
 
Alasql fast JavaScript in-memory SQL database
Alasql fast JavaScript in-memory SQL databaseAlasql fast JavaScript in-memory SQL database
Alasql fast JavaScript in-memory SQL databaseAndrey Gershun
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryWilliam Candillon
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleRaimonds Simanovskis
 
HTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayHTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayTed Drake
 

What's hot (20)

Django Multi-DB in Anger
Django Multi-DB in AngerDjango Multi-DB in Anger
Django Multi-DB in Anger
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
Using JavaScript in Drupal
Using JavaScript in DrupalUsing JavaScript in Drupal
Using JavaScript in Drupal
 
Core animation
Core animationCore animation
Core animation
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Tools that get you laid
Tools that get you laidTools that get you laid
Tools that get you laid
 
MongoDB's New Aggregation framework
MongoDB's New Aggregation frameworkMongoDB's New Aggregation framework
MongoDB's New Aggregation framework
 
Workload Replay in the Cloud: Secret Weapon for Cloud Migrations
Workload Replay in the Cloud: Secret Weapon for Cloud MigrationsWorkload Replay in the Cloud: Secret Weapon for Cloud Migrations
Workload Replay in the Cloud: Secret Weapon for Cloud Migrations
 
A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...A real-world Relay application in production - Stefano Masini - Codemotion Am...
A real-world Relay application in production - Stefano Masini - Codemotion Am...
 
Mssql to mysql - Anton Ivanov
Mssql to mysql - Anton IvanovMssql to mysql - Anton Ivanov
Mssql to mysql - Anton Ivanov
 
ERGroupware
ERGroupwareERGroupware
ERGroupware
 
Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application Benchx: An XQuery benchmarking web application
Benchx: An XQuery benchmarking web application
 
SQL and NoSQL Better Together in Alasql
SQL and NoSQL Better Together in AlasqlSQL and NoSQL Better Together in Alasql
SQL and NoSQL Better Together in Alasql
 
XQuery in the Cloud
XQuery in the CloudXQuery in the Cloud
XQuery in the Cloud
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Alasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User ManualAlasql JavaScript SQL Database Library: User Manual
Alasql JavaScript SQL Database Library: User Manual
 
Alasql fast JavaScript in-memory SQL database
Alasql fast JavaScript in-memory SQL databaseAlasql fast JavaScript in-memory SQL database
Alasql fast JavaScript in-memory SQL database
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQuery
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
HTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack DayHTML5 Hacking - Yahoo! Open Hack Day
HTML5 Hacking - Yahoo! Open Hack Day
 

Similar to Intro to Scala.js - Scala UG Cologne

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)Eugene Safronov
 
An introduction to Scala.js
An introduction to Scala.jsAn introduction to Scala.js
An introduction to Scala.jsKnoldus Inc.
 
Scala.js - yet another what..?
Scala.js - yet another what..?Scala.js - yet another what..?
Scala.js - yet another what..?Artur Skowroński
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Codemotion
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistpmanvi
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSAlberto Paro
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsScala Italy
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 

Similar to Intro to Scala.js - Scala UG Cologne (20)

Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)
 
Jet presentation
Jet presentationJet presentation
Jet presentation
 
An introduction to Scala.js
An introduction to Scala.jsAn introduction to Scala.js
An introduction to Scala.js
 
Scala.js - yet another what..?
Scala.js - yet another what..?Scala.js - yet another what..?
Scala.js - yet another what..?
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
Alberto Maria Angelo Paro - Isomorphic programming in Scala and WebDevelopmen...
 
Scala.js
Scala.jsScala.js
Scala.js
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Scala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologistScala and jvm_languages_praveen_technologist
Scala and jvm_languages_praveen_technologist
 
Scala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJSScala Italy 2015 - Hands On ScalaJS
Scala Italy 2015 - Hands On ScalaJS
 
Alberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.jsAlberto Paro - Hands on Scala.js
Alberto Paro - Hands on Scala.js
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

Intro to Scala.js - Scala UG Cologne

  • 1. Intro to Scala.js Marius Soutier Freelance Software Engineer @mariussoutier Write JavaScript in Scala
  • 2. What is Scala.js? Scala.js compiles Scala to JavaScript object HelloUg extends JSApp {
 override def main(): Unit = {
 // FP for the win
 var res, i = 0
 val values = js.Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
 while (i < values.length) {
 res = res + values(i)
 i += 1
 }
 println(res)
 }
 } $c_Lug_HelloUg$.prototype.main__V = (function() {
 var res = 0;
 var i = 0;
 var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 while ((i < $uI(values["length"]))) {
 res = ((res + $uI(values[i])) | 0);
 i = ((1 + i) | 0)
 };
 var x = res;
 var this$2 = $m_s_Console$();
 var this$3 = this$2.outVar$2;
 $as_Ljava_io_PrintStream(this$3.tl$1.get__O()).println__O__V(x)
 }); $e["ug"] = ($e["ug"] || {}); $e["ug"]["HelloUg"] = $m_Lug_HelloUg$;
  • 3. But Why? • Web development is moving to client-side apps,
 JavaScript is the browser’s only language • JavaScript is beyond broken • Maintaining a large JavaScript project can be difficult • Keeping up with JavaScript’s ecosystem is nigh- impossible
 (See JavaScript Drinking Game)
  • 4. Obligatory JavaScript: The Good Parts Reference But that’s enough JavaScript bashing for today
  • 5. Scala.js to the Rescue • We all love Scala • Type-safety, packages, traits, … • Rich standard library • Share code between backend and front-end • Full editor support (same file suffix) • Access to all JS libs and a lot of the Scala ecosystem
  • 7. • Size of compiled JavaScript • Compile Speed • JS libraries must be wrapped • Scala is developed with JVM in mind, some things just don't work in JS land, some JDK parts missing • Front-end developers might not want to learn Scala (slackers!) Drawbacks
  • 8. • Scala libraries available for Scala.js • Scalatags, ScalaCSS • Shapeless, Scalaz, Cats, Monocle • Sharing code inside a project via common cross-compiled
 sbt sub-project • Data exchange via JSON • upickle • JavaScript doesn't necessarily understand your JSON, 
 e.g. Longs aren't that long in JavaScript Sharing Code & Data
  • 9. How Does It Work? .scala .class .sjsir run/test ~fastOptJS fullOptJS Google Closure -opt.js -fastopt.js Rhino / Node.js Rhino / PhantomJS No DOM DOM -jsdeps.min.js jsDependencies ++= Seq(
 "org.webjars" % "jquery" % "1.10.2" / "jquery.js",
 "org.webjars" % "angularjs" % "1.4.8" / "angular.js" dependsOn "jquery.js"
 )
  • 10. Targeting JavaScript Scala / JVM JavaScript Byte, Short, Int, Float, Double Number Unit Undefined Char, Long Scala classes Custom Scala classes JavaScript class with @JSExport NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, StackOverflowError, … Undefined Reflection - String.split JS RegEx is different Pattern Matching on Byte, Short, Int, Float, Double Determined by runtime value, not type
  • 11. JavaScript Native Types JS-native Type Maps to Example JS js.FunctionN scala.FunctioN val fn: js.Function1[Int, Int] = (i: Int) => i * 2 var fn = function(i) {
 return i * 2;
 }; js.Array[T] Seq[T] js.Array(1, 2, 3) [1, 2, 3] js.Dictionary[T] mutable.Map[String, T] js.Dictionary("a" -> 1, "b" -> 2) {"a": 1, "b": 2} js.UndefOr[T] Option[T] val some: js.UndefOr[Int] = 1
 val none: js.UndefOr[Int] = js.undefined
 Option(1).orUndefined 1
 undefined 
 1 js.TupleN TupleN js.Tuple2(42, “Scala UG") [42, "Scala UG"]
  • 12. Dynamic JS When interacting with JavaScript libraries, its dynamic
 nature can’t always be ignored val guest = js.Dynamic.literal(
 name = "Scala User Group"
 ) But we can give it a nicer interface trait Guest extends js.Object {
 val name: String = js.native
 }
 
 object Guest {
 def apply(name: String): Guest =
 js.Dynamic.literal(name = name).asInstanceOf[Guest]
 } import js.Dynamic.{global => g}
 g.console.log(guest)
 
 val dom = g.document
 val p = dom.createElement("p")
 p.innerHTML = s"Hi ${guest.name}!"
 dom.getElementById("main").appendChild(p)
  • 13. Wrapping JS Libs (1) Read documentation and infer types
  • 14. Wrapping JS Libs (2) import scala.scalajs.js
 import scala.scalajs.js.annotation.JSName
 
 object Numeral {
 def apply(n: Double): Numeral = new Numeral(n)
 def apply(): Numeral = new Numeral(0)
 }
 
 @JSName("numeral")
 @js.native
 class Numeral(n: Double) extends js.Object {
 def format(formatString: String): String = js.native
 def unformat(formatString: String): Double = js.native
 
 def add(number: Double): Double = js.native
 def subtract(number: Double): Double = js.native
 def multiply(number: Double): Double = js.native
 def divide(number: Double): Double = js.native
 
 def value(): Double = js.native
 
 def difference(number: Double): Double = js.native
 } jsDependencies ++= Seq(
 "org.webjars" % "numeral-js" % "1.5.3-1" / "numeral.js" minified "min/numeral.min.js"
 ) Numeral(totalValue).format("0,0.00")
  • 15. Manipulating the DOM libraryDependencies ++= Seq(
 "org.scala-js" %%% "scalajs-dom" % "0.8.2"
 ) import org.scalajs.dom._
 val main = document.getElementById("main")
 val p = document.createElement("p")
 val text = document.createTextNode("Hi Scala User Group!")
 p.appendChild(text)
 main.appendChild(p)
  • 16. AJAX import org.scalajs.dom.ext.Ajax import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue 
 val eventualUsers =
 Ajax
 .get(url = "/users/")
 .map { xmlHttp =>
 xmlHttp.status match {
 case 200 =>
 import upickle.default._
 read[Seq[User]](xmlHttp.responseText)
 case other =>
 Seq.empty[User]
 }
 }
  • 17. • Export classes to JS for use from other JS code • Can even publish as NPM module Using Scala.js from JS @JSExport
 case class ExportedUser(
 @(JSExport@field) name: String,
 @(JSExport@field) email: String
 ) @JSExport
 @ScalaJSDefined
 class Foo extends js.Object {
 val x: Int = 4
 def bar(x: Int): Int = x + 1
 }