SlideShare a Scribd company logo
1 of 49
Scala.js for JavaScript
developers
Vitaly Tsaplin @ Adobe
© JavaBasel 2016
"If I were to pick a language to use today other than Java,
it would be Scala" by James Gosling
"I can honestly say if someone had shown me the Programming in Scala book by by
Martin Odersky I’d probably have never created Groovy." by James Strachan.
Agenda
• Scala.js? Are you serious?
• Scala fundamentals
• JavaScript interoperability
• Demo project
• QA
© JavaBasel 2016
What is Scala.js?
© JavaBasel 2016
JavaScript: Easy to prototype
• Easy to learn
• Runs virtually everywhere
• No need to compile anything
• Zoo of frameworks
© JavaBasel 2016
...but hard to scale
• Hard to reason about the code
• Refactoring is deadly
• Linting is not the same as static analysis
• Requires more tests
• Code completion is slow and unreliable
© JavaBasel 2016
Breaking the language barrier
• Virtual Machine written in JavaScript
– DoppioJVM
• Source-to-source compiler
– TypeScript
– Google Web Toolkit
– Scala.js (our hero)
© JavaBasel 2016
Why Scala.js?
• Mature, extensible and concise language
• Has many advanced features
• Object-oriented and functional
• Typesafe
• Code completion
• Refactoring
• Excellent tooling
• Interoperability with JavaScript
• Shared code
© JavaBasel 2016
Scala.js facts
• Incremental compilation is fast (1-2s)
• The generated code size is starting 45kB gzipped
• Existing Scala libraries can be leveraged
© JavaBasel 2016
Show me the code
// ES6
var xhr = new XMLHttpRequest();
xhr.open("GET",
"https://api.twitter.com/1.1/search" +
"tweets.json?q=%23scalajs");
xhr.onload = (e) => {
if (xhr.status === 200) {
var r = JSON.parse(xhr.responseText);
$("#tweets").html(parseTweets(r));
}
}
© JavaBasel 2016
Show me the code
// Scala
val xhr = new XMLHttpRequest()
xhr.open("GET",
"https://api.twitter.com/1.1/search" +
"tweets.json?q=%23scalajs");
xhr.onload = { (e: Event) =>
if (xhr.status == 200) {
val r = JSON.parse(xhr.responseText)
$("#tweets").html(parseTweets(r))
}
}
© JavaBasel 2016
Scala fundamentals
© JavaBasel 2016
Variables
// ES6
let x = 5;
const y = "Constant";
// Scala
var x = 5
val y = "Constant"
© JavaBasel 2016
Primitive types
Scala JavaScript
String string
Boolean boolean
Int, Short, Byte number
Double, Float number
Unit undefined
Null null
© JavaBasel 2016
Calculations
// ES6
const x = 5 / 3;// == 1.6666666666666667
// Scala
val x = 5 / 3 // == 1
val y = 5.0 / 3 // == 1.6666666666666667
val z = 5 / 3.0 // == 1.6666666666666667
© JavaBasel 2016
Type conversions
val x: Double = 3 // Ok!
val y: Int = 3.5 // Compile error
val z: Int = 3.5.toInt // Ok!
val a: Int = x // Compile error
val b: Int = x.toInt // Ok!
© JavaBasel 2016
String interpolation
// ES6
var name = "James";
console.log(`Hello, ${name}`);
// Scala
val name = "James"
println(s"Hello, $name")
val age = 25
val name = "James"
println(f"$name%s is $age%d")
© JavaBasel 2016
Functions
// ES6
function mult(x, y = 42.0) {
return x * y;
}
// Scala
def mult(x: Double, y: Double = 42.0): Double =
x * y
© JavaBasel 2016
Anonymous functions
// ES6
const f = (x, y) => x + y;
// Scala
val f = (x: Double, y: Double) => x + y
val p = Array("Fox", "jumped", "over", "me")
val l = p.map(s => s.length).sum
© JavaBasel 2016
Named parameters
// ES6
function vec({x = 0, y = 0}) {
return new Vec(x, y);
}
const v = vec({x: 8});
// Scala
def vec(x: Int = 0, y: Int = 0): Vec = {
new Vec(x, y)
}
val v = vec(y = 42)
© JavaBasel 2016
Rest parameters
// ES6
function sum(...args) {
return args.reduce((a, b) => a + b, 0);
}
// Scala
def sum(args: Double*): Int =
args.foldLeft(0)((a, b) => a + b)
© JavaBasel 2016
If-Else expression
// ES6
if (name === "") {
return 0;
} else {
return 1;
}
const res = (name === "") ? 0 : 1;
// Scala
val res = if (name == "") 0 else 1
© JavaBasel 2016
For loop
// ES6
let x = 0;
for (let i = 0; i < 100; i++)
x += i * i;
// Scala
var x = 0
for (i <- 0 until 100)
x += i * i
© JavaBasel 2016
For loop
// ES6
const p = ["Fox", "jumped", "over", "me"];
for (let s of p) {
console.log(`Word ${s}`);
}
// Scala
val p = Array("Fox", "jumped", "over", "me")
for (s <- p) {
println(s"Word $s")
}
© JavaBasel 2016
Pattern matching
// ES6
const animal = "Dog";
let description;
switch (animal) {
case "Cat":
description = "It's feline!";
break;
case "Dog":
case "Wolf":
description = "It's canine!";
break;
default:
description = "It's something else";
}
console.log(description);
© JavaBasel 2016
Pattern matching
// Scala
val animal = "Dog"
val description = animal match {
case "Cat =>
"It's feline!"
case "Dog" | "Wolf" =>
"It's canine!"
case _ => "It's something else"
}
println(description)
© JavaBasel 2016
Classes
// ES6
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
draw() {
}
}
const c = new Circle(5, 5, 42);
© JavaBasel 2016
Classes
// Scala
class Circle(x: Int, y: Int, val r: Int)
extends Shape(x, y) {
override def draw(): Unit = {
}
}
val c = new Circle(5, 5, 42)
© JavaBasel 2016
Case classes
// ES6
const p1= {first: "James", last: "Bond"};
const p2 = Object.assign({}, p1, {first: "John"});
// Scala
case class Person(first: String, last: String)
val p1 = Person("James", "Bond")
val p2 = p1.copy(first = "John")
© JavaBasel 2016
Objects
// ES6
const RandomGen = {
_rnd() {
return Math.random();
},
getRandomNumber() {
return this._rnd();
}
};
const r = RandomGen.getRandomNumber();
© JavaBasel 2016
Objects
// Scala
object RandomGen {
private val rnd = new Random()
def getRandomNumber: Double =
rnd.nextDouble()
}
val r = RandomGen.getRandomNumber
© JavaBasel 2016
Traits
// ES6
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
};
const Clickable = {
onClick() {
console.log("Clicked!");
}
};
class ClickableCircle extends Circle {}
Object.assign(ClickableCircle.prototype, Clickable);
const cc = new ClickableCircle(0, 0, 42);
cc.onClick();
© JavaBasel 2016
Traits
// Scala
class Circle(x: Int, y: Int, val r: Int)
extends Shape(x, y)
trait Clickable {
def onClick(): Unit = {
println("Clicked!")
}
}
class ClickableCircle(x: Int, y: Int, r: Int)
extends Circle(x, y, r) with Clickable
val cc = new ClickableCircle(0, 0, 42)
cc.onClick()
© JavaBasel 2016
Option
// ES6
function log(msg, context) {
let s;
if (context !== undefined)
s = `[${context}] ${msg}`;
else
s = msg;
console.log(s);
};
log("First message");
log("Second message", "debug");
© JavaBasel 2016
Option
// Scala
def log(msg: String,
context: Option[String] = None): Unit = {
val s = context match {
case Some(c) => s"[$c] $msg"
case None => msg
}
println(s)
}
log("First message")
log("Second message", Some("debug"))
© JavaBasel 2016
• Immutable and mutable implementations
• Scala always use immutable collections by default
Collections
© JavaBasel 2016
Implicit conversions
• Use conversion functions available in scope
• Safe alternative to monkey patching
// ES6
String.prototype.toDate = function() {
return convertToDate(this);
}
"2015-10-09".toDate();
// Scala
implicit class StrToDate(val s: String) {
def toDate = convertToDate(s)
}
"2015-10-09".toDate
© JavaBasel 2016
Future and Promise
• Future is a read-only placeholder object
• Promise is a writable, single-assignment container
© JavaBasel 2016
Future and Promise
// ES6
function onLoadPromise(img) {
if (img.complete) {
return Promise.resolve(img.src);
} else {
const p = new Promise((success) => {
img.onload = (e) => {
success(img.src);
};
});
return p;
}
}
const img = document.querySelector("#mapimage");
onLoadPromise(img).then(url =>
console.log(`Image ${url} loaded`)
);
© JavaBasel 2016
Future and Promise
// Scala
def onLoadFuture(img: HTMLImageElement) = {
if (img.complete) {
Future.successful(img.src)
} else {
val p = Promise[String]()
img.onload = { (e: Event) =>
p.success(img.src)
}
p.future
}
}
val img = dom.document.querySelector("#mapimage")
.asInstanceOf[HTMLImageElement]
onLoadFuture(img).foreach {
url => println(s"Image $url loaded")
}
© JavaBasel 2016
JavaScript interoperability
© JavaBasel 2016
Pre-defined JavaScript types
• Primitive types are represented by natural equivalents
• Other types have dedicated definitions
© JavaBasel 2016
js.Any
js.Object
js.Date
js.RegExp
js.Array[A]
js.Function
[T1, …, TN, R]
Js.ThisFunction
[T0, T1, …, TN, R]
js.Dictionary
Function types
• js.FunctionN[T1, ..., TN, R]
// Scala
val f: js.Function1[Double, Double] =
{ (x: Double) => x*x }
// ES6
var f = function(x) {
return x*x;
};
© JavaBasel 2016
Function types
• js.ThisFunctionN[T0, T1, ..., TN, R]
// Scala
val f: js.ThisFunction1[js.Object,
js.Number, js.Number] = ???
val o = new js.Object
val x = f(o, 4)
© JavaBasel 2016
Type correspondence
• Primitive types are mapped directly
• Function types
– js.FunctionN <–> scala.FunctionN
• Collection types
– js.Array[T] <–> mutable.Seq[T]
– js.Dictionary[T] <–> mutable.Map[String, T]
© JavaBasel 2016
Dynamically typed interface
• Allows to read and write any property
• Provides an entry point to the global scope
val document = js.Dynamic.global.document
val parent = document.getElementById("parent")
val p = document.createElement("p")
p.innerHTML = "Hello world!"
parent.appendChild(p)
js.Dynamic.literal(foo = 42, bar = "foobar")
js.Dynamic.literal("foo" -> 42, "bar" -> "foobar")
© JavaBasel 2016
Facade types for JavaScript APIs
• Inherit directly or indirectly from js.Any
• All concrete definitions must have js.native as body
trait Window extends js.Object {
val document: HTMLDocument = js.native
var location: String = js.native
def innerWidth: Int = js.native
def innerHeight: Int = js.native
def alert(message: String): Unit = js.native
}
© JavaBasel 2016
Exporting Scala.js APIs
package example
import scala.scalajs.js;
import js.annotation.JSExport;
@JSExport object HelloWorld {
@JSExport def main(): Unit = {
println("Hello world!")
}
}
HelloWorld().main();
© JavaBasel 2016
Demo project
© JavaBasel 2016
QA
© JavaBasel 2016

More Related Content

What's hot

Introduction to Scala for Java Programmers
Introduction to Scala for Java ProgrammersIntroduction to Scala for Java Programmers
Introduction to Scala for Java Programmerssbjug
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаAlina Dolgikh
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for AndroidTomáš Kypta
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorialKat Roque
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsBruce Schubert
 
Testing javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjsTesting javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjsJo Cranford
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Tomer Gabel
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scriptingmichid
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scalascalaconfjp
 
Client-side MVC with Backbone.js
Client-side MVC with Backbone.js Client-side MVC with Backbone.js
Client-side MVC with Backbone.js iloveigloo
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecordscalaconfjp
 

What's hot (20)

Introduction to Scala for Java Programmers
Introduction to Scala for Java ProgrammersIntroduction to Scala for Java Programmers
Introduction to Scala for Java Programmers
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим Клыга
 
Practical RxJava for Android
Practical RxJava for AndroidPractical RxJava for Android
Practical RxJava for Android
 
Ajax tutorial
Ajax tutorialAjax tutorial
Ajax tutorial
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart ExtensionsMoving from JFreeChart to JavaFX with JavaFX Chart Extensions
Moving from JFreeChart to JavaFX with JavaFX Chart Extensions
 
Testing javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjsTesting javascriptwithjasmine sydjs
Testing javascriptwithjasmine sydjs
 
Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)Scala Refactoring for Fun and Profit (Japanese subtitles)
Scala Refactoring for Fun and Profit (Japanese subtitles)
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
Scala
ScalaScala
Scala
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Solid and Sustainable Development in Scala
Solid and Sustainable Development in ScalaSolid and Sustainable Development in Scala
Solid and Sustainable Development in Scala
 
Client-side MVC with Backbone.js
Client-side MVC with Backbone.js Client-side MVC with Backbone.js
Client-side MVC with Backbone.js
 
Scala ActiveRecord
Scala ActiveRecordScala ActiveRecord
Scala ActiveRecord
 
Journey's end
Journey's endJourney's end
Journey's end
 

Viewers also liked

Blind SQL Injections. Достаточно ли хороши ваши тесты?
Blind SQL Injections. Достаточно ли хороши ваши тесты?Blind SQL Injections. Достаточно ли хороши ваши тесты?
Blind SQL Injections. Достаточно ли хороши ваши тесты?Igor Bondarenko
 
Переход на Scala: босиком по граблям
Переход на Scala: босиком по граблямПереход на Scala: босиком по граблям
Переход на Scala: босиком по граблямSveta Bozhko
 
Немного о кеше
Немного о кешеНемного о кеше
Немного о кешеDmitry Ignatiev
 
Introducing Scalate, the Scala Template Engine
Introducing Scalate, the Scala Template EngineIntroducing Scalate, the Scala Template Engine
Introducing Scalate, the Scala Template EngineJames Strachan
 
Scala in practice - 3 years later
Scala in practice - 3 years laterScala in practice - 3 years later
Scala in practice - 3 years laterpatforna
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspectiveSveta Bozhko
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaHermann Hueck
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Futuremircodotta
 
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)ScalaNsk
 
Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013ScalaNsk
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and countingManuel Bernhardt
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable LanguageMario Gleichmann
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Play Template Engine Based On Scala
Play Template Engine Based On ScalaPlay Template Engine Based On Scala
Play Template Engine Based On ScalaKnoldus Inc.
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San FranciscoMartin Odersky
 
Macro in Scala
Macro in ScalaMacro in Scala
Macro in Scalatakezoe
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016takezoe
 

Viewers also liked (20)

Scala.js в production
Scala.js в productionScala.js в production
Scala.js в production
 
Blind SQL Injections. Достаточно ли хороши ваши тесты?
Blind SQL Injections. Достаточно ли хороши ваши тесты?Blind SQL Injections. Достаточно ли хороши ваши тесты?
Blind SQL Injections. Достаточно ли хороши ваши тесты?
 
Переход на Scala: босиком по граблям
Переход на Scala: босиком по граблямПереход на Scala: босиком по граблям
Переход на Scala: босиком по граблям
 
Немного о кеше
Немного о кешеНемного о кеше
Немного о кеше
 
Introducing Scalate, the Scala Template Engine
Introducing Scalate, the Scala Template EngineIntroducing Scalate, the Scala Template Engine
Introducing Scalate, the Scala Template Engine
 
Scala in practice - 3 years later
Scala in practice - 3 years laterScala in practice - 3 years later
Scala in practice - 3 years later
 
Intro scala for rubyists (ironhack)
Intro scala for rubyists (ironhack)Intro scala for rubyists (ironhack)
Intro scala for rubyists (ironhack)
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Golang from Scala developer’s perspective
Golang from Scala developer’s perspectiveGolang from Scala developer’s perspective
Golang from Scala developer’s perspective
 
Reactive Access to MongoDB from Scala
Reactive Access to MongoDB from ScalaReactive Access to MongoDB from Scala
Reactive Access to MongoDB from Scala
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)
Павел Павлов - Scala для Java программистов (JavaDay Nsk 28.11.2013)
 
Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013Павел Павлов - Scala для профессионалов - Joker 2013
Павел Павлов - Scala для профессионалов - Joker 2013
 
Six years of Scala and counting
Six years of Scala and countingSix years of Scala and counting
Six years of Scala and counting
 
Scala - A Scalable Language
Scala - A Scalable LanguageScala - A Scalable Language
Scala - A Scalable Language
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Play Template Engine Based On Scala
Play Template Engine Based On ScalaPlay Template Engine Based On Scala
Play Template Engine Based On Scala
 
Scala Days San Francisco
Scala Days San FranciscoScala Days San Francisco
Scala Days San Francisco
 
Macro in Scala
Macro in ScalaMacro in Scala
Macro in Scala
 
Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016Scala Frameworks for Web Application 2016
Scala Frameworks for Web Application 2016
 

Similar to Scala.js

Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneMarius Soutier
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
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
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development toolsSimon Kim
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009tolmasky
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Arnaud Giuliani
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6Solution4Future
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?Sarah Mount
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 

Similar to Scala.js (20)

Intro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG CologneIntro to Scala.js - Scala UG Cologne
Intro to Scala.js - Scala UG Cologne
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Full Stack Scala
Full Stack ScalaFull Stack Scala
Full Stack Scala
 
Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)Scala js (kyiv js 30-01)
Scala js (kyiv js 30-01)
 
A few good JavaScript development tools
A few good JavaScript development toolsA few good JavaScript development tools
A few good JavaScript development tools
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009Cappuccino @ JSConf 2009
Cappuccino @ JSConf 2009
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala
ScalaScala
Scala
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6JavaScript - new features in ECMAScript 6
JavaScript - new features in ECMAScript 6
 
Json generation
Json generationJson generation
Json generation
 
Scala overview
Scala overviewScala overview
Scala overview
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 

Recently uploaded

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Recently uploaded (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Scala.js

  • 1. Scala.js for JavaScript developers Vitaly Tsaplin @ Adobe © JavaBasel 2016 "If I were to pick a language to use today other than Java, it would be Scala" by James Gosling "I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky I’d probably have never created Groovy." by James Strachan.
  • 2. Agenda • Scala.js? Are you serious? • Scala fundamentals • JavaScript interoperability • Demo project • QA © JavaBasel 2016
  • 3. What is Scala.js? © JavaBasel 2016
  • 4. JavaScript: Easy to prototype • Easy to learn • Runs virtually everywhere • No need to compile anything • Zoo of frameworks © JavaBasel 2016
  • 5. ...but hard to scale • Hard to reason about the code • Refactoring is deadly • Linting is not the same as static analysis • Requires more tests • Code completion is slow and unreliable © JavaBasel 2016
  • 6. Breaking the language barrier • Virtual Machine written in JavaScript – DoppioJVM • Source-to-source compiler – TypeScript – Google Web Toolkit – Scala.js (our hero) © JavaBasel 2016
  • 7. Why Scala.js? • Mature, extensible and concise language • Has many advanced features • Object-oriented and functional • Typesafe • Code completion • Refactoring • Excellent tooling • Interoperability with JavaScript • Shared code © JavaBasel 2016
  • 8. Scala.js facts • Incremental compilation is fast (1-2s) • The generated code size is starting 45kB gzipped • Existing Scala libraries can be leveraged © JavaBasel 2016
  • 9. Show me the code // ES6 var xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.twitter.com/1.1/search" + "tweets.json?q=%23scalajs"); xhr.onload = (e) => { if (xhr.status === 200) { var r = JSON.parse(xhr.responseText); $("#tweets").html(parseTweets(r)); } } © JavaBasel 2016
  • 10. Show me the code // Scala val xhr = new XMLHttpRequest() xhr.open("GET", "https://api.twitter.com/1.1/search" + "tweets.json?q=%23scalajs"); xhr.onload = { (e: Event) => if (xhr.status == 200) { val r = JSON.parse(xhr.responseText) $("#tweets").html(parseTweets(r)) } } © JavaBasel 2016
  • 12. Variables // ES6 let x = 5; const y = "Constant"; // Scala var x = 5 val y = "Constant" © JavaBasel 2016
  • 13. Primitive types Scala JavaScript String string Boolean boolean Int, Short, Byte number Double, Float number Unit undefined Null null © JavaBasel 2016
  • 14. Calculations // ES6 const x = 5 / 3;// == 1.6666666666666667 // Scala val x = 5 / 3 // == 1 val y = 5.0 / 3 // == 1.6666666666666667 val z = 5 / 3.0 // == 1.6666666666666667 © JavaBasel 2016
  • 15. Type conversions val x: Double = 3 // Ok! val y: Int = 3.5 // Compile error val z: Int = 3.5.toInt // Ok! val a: Int = x // Compile error val b: Int = x.toInt // Ok! © JavaBasel 2016
  • 16. String interpolation // ES6 var name = "James"; console.log(`Hello, ${name}`); // Scala val name = "James" println(s"Hello, $name") val age = 25 val name = "James" println(f"$name%s is $age%d") © JavaBasel 2016
  • 17. Functions // ES6 function mult(x, y = 42.0) { return x * y; } // Scala def mult(x: Double, y: Double = 42.0): Double = x * y © JavaBasel 2016
  • 18. Anonymous functions // ES6 const f = (x, y) => x + y; // Scala val f = (x: Double, y: Double) => x + y val p = Array("Fox", "jumped", "over", "me") val l = p.map(s => s.length).sum © JavaBasel 2016
  • 19. Named parameters // ES6 function vec({x = 0, y = 0}) { return new Vec(x, y); } const v = vec({x: 8}); // Scala def vec(x: Int = 0, y: Int = 0): Vec = { new Vec(x, y) } val v = vec(y = 42) © JavaBasel 2016
  • 20. Rest parameters // ES6 function sum(...args) { return args.reduce((a, b) => a + b, 0); } // Scala def sum(args: Double*): Int = args.foldLeft(0)((a, b) => a + b) © JavaBasel 2016
  • 21. If-Else expression // ES6 if (name === "") { return 0; } else { return 1; } const res = (name === "") ? 0 : 1; // Scala val res = if (name == "") 0 else 1 © JavaBasel 2016
  • 22. For loop // ES6 let x = 0; for (let i = 0; i < 100; i++) x += i * i; // Scala var x = 0 for (i <- 0 until 100) x += i * i © JavaBasel 2016
  • 23. For loop // ES6 const p = ["Fox", "jumped", "over", "me"]; for (let s of p) { console.log(`Word ${s}`); } // Scala val p = Array("Fox", "jumped", "over", "me") for (s <- p) { println(s"Word $s") } © JavaBasel 2016
  • 24. Pattern matching // ES6 const animal = "Dog"; let description; switch (animal) { case "Cat": description = "It's feline!"; break; case "Dog": case "Wolf": description = "It's canine!"; break; default: description = "It's something else"; } console.log(description); © JavaBasel 2016
  • 25. Pattern matching // Scala val animal = "Dog" val description = animal match { case "Cat => "It's feline!" case "Dog" | "Wolf" => "It's canine!" case _ => "It's something else" } println(description) © JavaBasel 2016
  • 26. Classes // ES6 class Circle extends Shape { constructor(x, y, r) { super(x, y); this.r = r; } draw() { } } const c = new Circle(5, 5, 42); © JavaBasel 2016
  • 27. Classes // Scala class Circle(x: Int, y: Int, val r: Int) extends Shape(x, y) { override def draw(): Unit = { } } val c = new Circle(5, 5, 42) © JavaBasel 2016
  • 28. Case classes // ES6 const p1= {first: "James", last: "Bond"}; const p2 = Object.assign({}, p1, {first: "John"}); // Scala case class Person(first: String, last: String) val p1 = Person("James", "Bond") val p2 = p1.copy(first = "John") © JavaBasel 2016
  • 29. Objects // ES6 const RandomGen = { _rnd() { return Math.random(); }, getRandomNumber() { return this._rnd(); } }; const r = RandomGen.getRandomNumber(); © JavaBasel 2016
  • 30. Objects // Scala object RandomGen { private val rnd = new Random() def getRandomNumber: Double = rnd.nextDouble() } val r = RandomGen.getRandomNumber © JavaBasel 2016
  • 31. Traits // ES6 class Circle extends Shape { constructor(x, y, r) { super(x, y); this.r = r; } }; const Clickable = { onClick() { console.log("Clicked!"); } }; class ClickableCircle extends Circle {} Object.assign(ClickableCircle.prototype, Clickable); const cc = new ClickableCircle(0, 0, 42); cc.onClick(); © JavaBasel 2016
  • 32. Traits // Scala class Circle(x: Int, y: Int, val r: Int) extends Shape(x, y) trait Clickable { def onClick(): Unit = { println("Clicked!") } } class ClickableCircle(x: Int, y: Int, r: Int) extends Circle(x, y, r) with Clickable val cc = new ClickableCircle(0, 0, 42) cc.onClick() © JavaBasel 2016
  • 33. Option // ES6 function log(msg, context) { let s; if (context !== undefined) s = `[${context}] ${msg}`; else s = msg; console.log(s); }; log("First message"); log("Second message", "debug"); © JavaBasel 2016
  • 34. Option // Scala def log(msg: String, context: Option[String] = None): Unit = { val s = context match { case Some(c) => s"[$c] $msg" case None => msg } println(s) } log("First message") log("Second message", Some("debug")) © JavaBasel 2016
  • 35. • Immutable and mutable implementations • Scala always use immutable collections by default Collections © JavaBasel 2016
  • 36. Implicit conversions • Use conversion functions available in scope • Safe alternative to monkey patching // ES6 String.prototype.toDate = function() { return convertToDate(this); } "2015-10-09".toDate(); // Scala implicit class StrToDate(val s: String) { def toDate = convertToDate(s) } "2015-10-09".toDate © JavaBasel 2016
  • 37. Future and Promise • Future is a read-only placeholder object • Promise is a writable, single-assignment container © JavaBasel 2016
  • 38. Future and Promise // ES6 function onLoadPromise(img) { if (img.complete) { return Promise.resolve(img.src); } else { const p = new Promise((success) => { img.onload = (e) => { success(img.src); }; }); return p; } } const img = document.querySelector("#mapimage"); onLoadPromise(img).then(url => console.log(`Image ${url} loaded`) ); © JavaBasel 2016
  • 39. Future and Promise // Scala def onLoadFuture(img: HTMLImageElement) = { if (img.complete) { Future.successful(img.src) } else { val p = Promise[String]() img.onload = { (e: Event) => p.success(img.src) } p.future } } val img = dom.document.querySelector("#mapimage") .asInstanceOf[HTMLImageElement] onLoadFuture(img).foreach { url => println(s"Image $url loaded") } © JavaBasel 2016
  • 41. Pre-defined JavaScript types • Primitive types are represented by natural equivalents • Other types have dedicated definitions © JavaBasel 2016 js.Any js.Object js.Date js.RegExp js.Array[A] js.Function [T1, …, TN, R] Js.ThisFunction [T0, T1, …, TN, R] js.Dictionary
  • 42. Function types • js.FunctionN[T1, ..., TN, R] // Scala val f: js.Function1[Double, Double] = { (x: Double) => x*x } // ES6 var f = function(x) { return x*x; }; © JavaBasel 2016
  • 43. Function types • js.ThisFunctionN[T0, T1, ..., TN, R] // Scala val f: js.ThisFunction1[js.Object, js.Number, js.Number] = ??? val o = new js.Object val x = f(o, 4) © JavaBasel 2016
  • 44. Type correspondence • Primitive types are mapped directly • Function types – js.FunctionN <–> scala.FunctionN • Collection types – js.Array[T] <–> mutable.Seq[T] – js.Dictionary[T] <–> mutable.Map[String, T] © JavaBasel 2016
  • 45. Dynamically typed interface • Allows to read and write any property • Provides an entry point to the global scope val document = js.Dynamic.global.document val parent = document.getElementById("parent") val p = document.createElement("p") p.innerHTML = "Hello world!" parent.appendChild(p) js.Dynamic.literal(foo = 42, bar = "foobar") js.Dynamic.literal("foo" -> 42, "bar" -> "foobar") © JavaBasel 2016
  • 46. Facade types for JavaScript APIs • Inherit directly or indirectly from js.Any • All concrete definitions must have js.native as body trait Window extends js.Object { val document: HTMLDocument = js.native var location: String = js.native def innerWidth: Int = js.native def innerHeight: Int = js.native def alert(message: String): Unit = js.native } © JavaBasel 2016
  • 47. Exporting Scala.js APIs package example import scala.scalajs.js; import js.annotation.JSExport; @JSExport object HelloWorld { @JSExport def main(): Unit = { println("Hello world!") } } HelloWorld().main(); © JavaBasel 2016