SlideShare una empresa de Scribd logo
1 de 45
Descargar para leer sin conexión
JAVA8 / SCALA
Difference points & innovation streams
Ruslan Shevchenko. <ruslan@shevchenko.kiev.ua>
https://github.com/rssh
@rssh1
JAVA / SCALA
• Java & Scala significantly different
• Exists innovations: scala => java & java=>scala
• What language I must learn ?
• All of them !
SCALA JAVA8
public class Person
{
private String firstName;
private String lastName;
String getFirstName()
{ return firstName; }
void setFirstName(String v)
{ firstName = v; }
………………….
int hashCode() {
if (firstName==null) {
if (secondName==null) {
return 0;
} else {
return secondName.hashCode();
}
} else{
if (secondName==null) {
}
}
}
boolean equals() { …. }
}
case class Person
(
firstName: String
lastName: String
)
SCALA JAVA8
public class Person
extends DTOBase
{
public String firstName;
public String lastName;
}
case class Person
(
firstName: String
lastName: String
)
SCALA => JAVA
Similar:
lambda-expressions
traits / default methods
collections API with hight-order functions
LAMBDA EXPRESSIONS
list.sort((x,y)-> {
int cmp = x.lastName.compareTo(y.lastName);
return cmp!=0 ? cmp : x.firstName.compareTo(y.firstName)
}
list.sort((x,y) => {
val cmp = x.lastName.compareTo(y.lastName)
if (cmp!=0) cmp else x.firstName.compareTo(y.lastName)
}
Java
Scala
LAMBDA EXPRESSIONS
var (maxFirstLen, maxSecondLen) = (0,0)
list.foreach{
x => maxFirstLen = max(maxFirstLen, x.firstName.length)
maxSecondLen = max(maxSecondLen, x.secondName.length)
}
Java
Scala
Closures can’t modify environment context
…………………….
TRAITS/DEFAULT METHODS
trait AsyncInput[T]
{
def onReceive(acceptor:T=>()): Unit
def read: Future[T] = {
Promise p = Promise[T]()
onReceive(p.complete(_))
p.future
}
}
interface AsyncInput<T>
{
void onReceive(Acceptor<T> acceptor)
default void read(): Future<T> {
final CompletableFuture<T> promise =
new CompletableFuture<>();
onReceive( x -> promise.complete(x) );
return promise;
}
}
Scala Java
TRAITS/DEFAULT METHODS
trait LoggedAsyncInput[T]
{
this:AsyncInput =>
override def onReceive(acceptor:T => ()) =
super.onReceive(x => {
println(s“received:${x}”)
acceptor(x) })
}
Scala
Java
aspects ? …
TRAITS/DEFAULT METHODS
trait LoggedAsyncInput[T]
{
override def onReceive(acceptor:T => ()) =
super.onReceive(x => {
println(s“received:${x}”)
acceptor(x) })
}
Scala
Java
aspects ? …
trait MyToString
{
override def toString = s”[${super.toString}]”
}
TRAITS/DEFAULT METHODS
Java default interface:
dispatch across class/interface hierarchy
Scala traits
building hierarchy with process of linearization
STREAMING COLLECTIONS
persons.stream().filter(
x -> x.firstName.equals(”Jon”)
).collect(Collectors.toList())
persons.filter(_.firstName == “Jon”)
Java
Scala
STREAMING COLLECTIONS
persons.stream().filter(
x -> x.firstName.equals(”Jon”)
).collect(Collectors.toList())
Java
Reason - existing API
Don’t want to mix old and new API in one
Operation composition without reiterating.
PARALLEL
persons.parallelStream().filter(
x -> x.firstName.equals(”Jon”)
).collect(Collectors.toList())
persons.par.filter(_.firstName == “Jon”)
Java
Scala
SQL
..??***8dc
persons.filter(_.firstName === “Jon”)
Scala (slick)
Java ?
?
SQL
..??***8dc
persons.filter(_.firstName === “Jon”)
Scala (slick)
Java (http://jinq.org)
dbStream(em,Person.class).filter(
x -> x.firstName.equals(“Jon”)
).list
SQL (INSIDE ?)
persons.filter(_.firstName === “Jon”).toList
Scala (slick)
TableQuery[Expr[Person]]
Expr[String], Expr[StringConstant] => Expr[Boolean]
SQL (INSIDE ?)
persons.filter(_.firstName === “Jon”).toList
Scala (slick)
TableQuery[Expr[Person]]
Expr[String], Expr[StringConstant] => Expr[Boolean]
Query[Expr[T]], Expr[Boolean] => Query[Expr[T]]
Query { … generateSql( .. ) }
SQL (INSIDE)
..??***8dc
Java (http://jinq.org)
dbStream(em,Person.class).filter(
x -> x.firstName.equals(“Jon”)
).list
DbStream<Person>
Person => Boolean
SQL (INSIDE)
..??***8dc
Java (http://jinq.org)
dbStream(em,Person.class).filter(
x -> x.firstName.equals(“Jon”)
).list
Person => Boolean
for sql generation we need:
analyse bytecode
symbolic interpretation
collect trace
generate sql
// runtime-only, not very fast
SQL (INSIDE)
Java (http://jinq.org)
// runtime-only, not very fast
complex, state-of-the-art technology
all work is in runtime
unable to check function correctness in compile-time
Scala (slick)
relatively simple
compile-time analysis, runtime generation
verification in compile time
JAVA => SCALA: SAM
trait AsyncInputOutput[T]
{
def onReceive(acceptor:T=>()): Unit
def onSend(generator: ()=>T): Unit
}
interface AsyncInputOutput<T>
{
void onReceive(Acceptor<T> acceptor)
void onSend(Generator<T> generator)
………………
}
Scala Java
SAM
• SAM-type =Type with Single Abstract Method
• Method require SAM-type => we can pass lambda-
expression to one.
• In scala:
• 2.11 — with -Xexperimental
• 2.12 — by default
SAM
trait AsyncInputOutput[T]
{
Function1.class
def onReceive(acceptor:T=>()): Unit
Function1.class
def onSend(generator: ()=>T): Unit
}
interface AsyncInputOutput<T>
{
Acceptor.class
void onReceive(Acceptor<T> acceptor)
Generator.class
void onSend(Generator<T> generator)
………………
}
Scala: JVM Java
JIT inlining impossible Jit inlining is possible
SCALA=>JAVA; JAVA=>SCALA
• Java use ‘additional’ streaming API [not ideal, better
than before]
• Scala library can’t utilize SAM conversion [not ideal,
better than before]
• So, we have place for something 3-rd ?
• Evolution: all ‘ideal’ shifts ….
FUTURE EVOLUTION
• 2 Groups
• which will be integrated in java 9,10, 11, .. if exists.
• [ FORTRAN 90 is object-oriented. Do you know this (?)]
• case classes, type inheritance.
• which represent essential different aspect, not present in java
CASE CLASSES
..??***8dc
case class Person(firstName: String, lastName: String)
p match {
case Person(“Jon”,”Galt” ) => “Hi, who are you ?”
case Person(firstName, lastName) =>
s”Hi, ${firstName}, ${lastName}”
case _ => “You are not person”
}
ML-style pattern matching, 1973
scala,
kotlin,
ceylon,
swift
FUTURE EVOLUTION
• essential different aspect, not present in java:
• internal DSL
• flexible syntax
• call by name
• macros
• Variance
• strong typing
• implicit context
FLEXIBLE SYNTAX
..??***8dc
def +++(x:Int, y:Int) = x*x*y*y
1 to 100 == 1.to(100)
future(1) та future{1}
def until(cond: =>Boolean)(body: => Unit): Unit
CALL BY NAME
..??***8dc
def dountil(cond: =>Boolean)(body: => Unit): Unit =
{
var quit = false;
while(!quit) {
body
quit = !cond
}
}
First introduced in Algol 68
var x = 0
dountil(x != 10)(x+=1)
OWN SYNTAX
..??***8dc
object Do
{
def apply(body: =>Unit) = new DoBody(body)
}
class DoBody(body: => Unit)
{
def until(cond: =>Boolean): Unit =
{ body; while(!cond) body }
}
Do { x = x+1 } until (x<10)
BASIC DSL:)
..??***8dc
object Lunar extends Baysick {
def main(args:Array[String]) = {
10 PRINT "Welcome to Baysick Lunar Lander v0.9"
20 LET ('dist := 100)
30 LET ('v := 1)
40 LET ('fuel := 1000)
50 LET ('mass := 1000)
60 PRINT "You are drifting towards the moon."
70 PRINT "You must decide how much fuel to burn."
80 PRINT "To accelerate enter a positive number"
90 PRINT "To decelerate a negative"
100 PRINT "Distance " % 'dist % "km, " % "Velocity " % 'v % "km/s, " % "Fuel " % 'fuel
110 INPUT 'burn
120 IF ABS('burn) <= 'fuelTHEN 150
130 PRINT "You don't have that much fuel"
140 GOTO 100
ogus.me/2009/03/26/baysick-a-scala-dsl-implementing-basic/
..??***8dccollection.foreach(x => doSomething)
‘FOR’ SPECIAL SYNTAX
..??***8dcfor( x <- collection) doSomething
=
..??***8dc
for(x <- fun1 if (x.isGood);
y <- fun2(x) ) yield z(x,y)
=
..??***8dc
fun1.withFilter(_.isGood).
flatMap(x =>
fun2.map(y=>z(x,y)))
..??***8dccollection.foreach(x => doSomething)
‘FOR’ SPECIAL SYNTAX
..??***8dcfor( x <- collection) doSomething
=
..??***8dc
for(x <- collection)
yield something =
..??***8dccollection.map( x => something)
‘FOR’ SPECIAL SYNTAX
..??***8dc
=
..??**8dc
for(r <- rows;
c <- cell(r) ) ….
rows.flatMap(r =>
cell.map(c =>….))
..??***8dcfor(x <- c if p(x)) …. =
..??***8dcc.withFilter(x->p(x)) …
..??***8dccollection.foreach(x => doSomething)
‘FOR’ SPECIAL SYNTAX
..??***8dcfor( x <- collection) doSomething
=
..??***8dc
for(x <- fun1 if (x.isGood);
y <- fun2(x) ) yield z(x,y)
=
..??***8dc
fun1.withFilter(_.isGood).
flatMap(x =>
fun2.map(y=>z(x,y)))
FOR-SYNTAX
• own foreach: possible to use ‘for’
• ‘Monadic interfaces’
• //foreach, map, flatMap, withFilter
• // scala-virtualized (not in standard)
• define own function for all syntax constructions
IMPLICIT
implicit def f(x): y
Use x as y
add ‘own’ methods to existing classes
pass context
define type-guided expressions
FUTURE: MONADIC
..??***8dc
for( x <- Future{ calculate x };
y <- Future{ calculate y } ) yield x(x,y)
Future[T]
foreach — do something after competition
map
flatMap — future composition
MACROS
..??***8dc
object Log {
def apply(msg: String): Unit = macro applyImpl
def applyImpl(c: Context)(msg: c.Expr[String]):c.Expr[Unit] =
{
import c.universe._
val tree = q"""if (Log.enabled) {
Log.log(${msg})
}
"""
c.Expr[Unit](tree)
}
Log(msg)
if (Log.enabled) {
Log.log(msg)
}
MACROS
Reduce boilerplate code
Fast code generation for HPC
Deep AST transformations
example: async
ASYNC AS MACROS
..??***8dc
async {
val x = async{ long-running-code-x }
val y = async{ long-running-code-y }
val z = await(x) + await(y)
}
Rewritten as state machine without blocking
Implemented as library (without language change)
async: T => Future[T ]
await: Future[T] =>T
MACROS
async/await
jscala (generate javascript)
miniboxing (analog @specialized)
JAVA/SCALA
• Java - stable domain, mapped to classes and objects.
• Scala - in complex area, where new level of
abstractions needed.
• In the beginning of PL
evolution, but totally new dimension
THANKS FOR ATTENTION
Ruslan Shevchenko <ruslan@shevchenko.kiev.ua>
@rssh1
https://github.com/rssh

Más contenido relacionado

La actualidad más candente

Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Predictably
PredictablyPredictably
Predictablyztellman
 
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
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers輝 子安
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
The Macronomicon
The MacronomiconThe Macronomicon
The MacronomiconMike Fogus
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopPublicis Sapient Engineering
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorFedor Lavrentyev
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.Mike Fogus
 

La actualidad más candente (20)

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Predictably
PredictablyPredictably
Predictably
 
All about scala
All about scalaAll about scala
All about scala
 
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
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
Scala
ScalaScala
Scala
 
Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
scala
scalascala
scala
 
The Macronomicon
The MacronomiconThe Macronomicon
The Macronomicon
 
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour HadoopOSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
OSDC.fr 2012 :: Cascalog : progammation logique pour Hadoop
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev FedorProgramming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
Programming Java - Lection 07 - Puzzlers - Lavrentyev Fedor
 
Code as data as code.
Code as data as code.Code as data as code.
Code as data as code.
 
ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 

Destacado

リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)
リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)
リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)BIGLOBE Tech Talk
 
Инфоком ЛТД Беспилотное наземное транспортное средство
Инфоком ЛТД Беспилотное наземное транспортное средствоИнфоком ЛТД Беспилотное наземное транспортное средство
Инфоком ЛТД Беспилотное наземное транспортное средствоmax_ko
 
Survey of restful web services frameworks
Survey of restful web services frameworksSurvey of restful web services frameworks
Survey of restful web services frameworksVijay Prasad Gupta
 
ドワンゴでのScala活用事例「ニコニコandroid」
ドワンゴでのScala活用事例「ニコニコandroid」ドワンゴでのScala活用事例「ニコニコandroid」
ドワンゴでのScala活用事例「ニコニコandroid」Satoshi Goto
 
色んなScalaを調べてみた
色んなScalaを調べてみた色んなScalaを調べてみた
色んなScalaを調べてみたJiro Hiraiwa
 
Scala採用の背景とその後 @ hitomedia night #5
Scala採用の背景とその後 @ hitomedia night #5Scala採用の背景とその後 @ hitomedia night #5
Scala採用の背景とその後 @ hitomedia night #5Jiro Hiraiwa
 
Play2実践tips集
Play2実践tips集Play2実践tips集
Play2実践tips集takezoe
 
アドテク企業のScala導入について振り返るlt
アドテク企業のScala導入について振り返るltアドテク企業のScala導入について振り返るlt
アドテク企業のScala導入について振り返るltJiro Hiraiwa
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Scalaの現状と今後
Scalaの現状と今後Scalaの現状と今後
Scalaの現状と今後Kota Mizushima
 
アクターモデルについて
アクターモデルについてアクターモデルについて
アクターモデルについてTakamasa Mitsuji
 
Scala@SmartNews_20150221
Scala@SmartNews_20150221Scala@SmartNews_20150221
Scala@SmartNews_20150221Shigekazu Takei
 
JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8Dmitry Kornilov
 
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalaビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalatakezoe
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVMPhil Calçado
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 

Destacado (20)

リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)
リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)
リーンでアジャイルにAndroidアプリ開発をしてみた!(NECビッグローブ ABC向け資料)
 
Инфоком ЛТД Беспилотное наземное транспортное средство
Инфоком ЛТД Беспилотное наземное транспортное средствоИнфоком ЛТД Беспилотное наземное транспортное средство
Инфоком ЛТД Беспилотное наземное транспортное средство
 
Rest overview briefing
Rest  overview briefingRest  overview briefing
Rest overview briefing
 
Survey of restful web services frameworks
Survey of restful web services frameworksSurvey of restful web services frameworks
Survey of restful web services frameworks
 
ドワンゴでのScala活用事例「ニコニコandroid」
ドワンゴでのScala活用事例「ニコニコandroid」ドワンゴでのScala活用事例「ニコニコandroid」
ドワンゴでのScala活用事例「ニコニコandroid」
 
色んなScalaを調べてみた
色んなScalaを調べてみた色んなScalaを調べてみた
色んなScalaを調べてみた
 
Scala採用の背景とその後 @ hitomedia night #5
Scala採用の背景とその後 @ hitomedia night #5Scala採用の背景とその後 @ hitomedia night #5
Scala採用の背景とその後 @ hitomedia night #5
 
Play2実践tips集
Play2実践tips集Play2実践tips集
Play2実践tips集
 
アドテク企業のScala導入について振り返るlt
アドテク企業のScala導入について振り返るltアドテク企業のScala導入について振り返るlt
アドテク企業のScala導入について振り返るlt
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Scalaの現状と今後
Scalaの現状と今後Scalaの現状と今後
Scalaの現状と今後
 
アクターモデルについて
アクターモデルについてアクターモデルについて
アクターモデルについて
 
Scala@SmartNews_20150221
Scala@SmartNews_20150221Scala@SmartNews_20150221
Scala@SmartNews_20150221
 
JSON Support in Java EE 8
JSON Support in Java EE 8JSON Support in Java EE 8
JSON Support in Java EE 8
 
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscalaビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
ビズリーチの新サービスをScalaで作ってみた 〜マイクロサービスの裏側 #jissenscala
 
From a monolithic Ruby on Rails app to the JVM
From a monolithic  Ruby on Rails app  to the JVMFrom a monolithic  Ruby on Rails app  to the JVM
From a monolithic Ruby on Rails app to the JVM
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Similar a JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 WorldDaniel Blyth
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)William Narmontas
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 

Similar a JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream (20)

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - Stockholm
 
Scala in a Java 8 World
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
An Introduction to Scala (2014)
An Introduction to Scala (2014)An Introduction to Scala (2014)
An Introduction to Scala (2014)
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 

Más de Ruslan Shevchenko

Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Ruslan Shevchenko
 
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Papers We Love / Kyiv :  PAXOS (and little about other consensuses )Papers We Love / Kyiv :  PAXOS (and little about other consensuses )
Papers We Love / Kyiv : PAXOS (and little about other consensuses )Ruslan Shevchenko
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolutionRuslan Shevchenko
 
{co/contr} variance from LSP
{co/contr} variance  from LSP{co/contr} variance  from LSP
{co/contr} variance from LSPRuslan Shevchenko
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Ruslan Shevchenko
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisRuslan Shevchenko
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applicationsRuslan Shevchenko
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platformRuslan Shevchenko
 
Behind OOD: domain modelling in post-OO world.
Behind OOD:  domain modelling in post-OO world.Behind OOD:  domain modelling in post-OO world.
Behind OOD: domain modelling in post-OO world.Ruslan Shevchenko
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scalaRuslan Shevchenko
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N yearsRuslan Shevchenko
 

Más de Ruslan Shevchenko (20)

Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]Embedding Generic Monadic Transformer into Scala. [Tfp2022]
Embedding Generic Monadic Transformer into Scala. [Tfp2022]
 
Svitla talks 2021_03_25
Svitla talks 2021_03_25Svitla talks 2021_03_25
Svitla talks 2021_03_25
 
Akka / Lts behavior
Akka / Lts behaviorAkka / Lts behavior
Akka / Lts behavior
 
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
Papers We Love / Kyiv :  PAXOS (and little about other consensuses )Papers We Love / Kyiv :  PAXOS (and little about other consensuses )
Papers We Love / Kyiv : PAXOS (and little about other consensuses )
 
Scala / Technology evolution
Scala  / Technology evolutionScala  / Technology evolution
Scala / Technology evolution
 
{co/contr} variance from LSP
{co/contr} variance  from LSP{co/contr} variance  from LSP
{co/contr} variance from LSP
 
N flavors of streaming
N flavors of streamingN flavors of streaming
N flavors of streaming
 
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
Scala-Gopher: CSP-style programming techniques with idiomatic Scala.
 
SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Why scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with thisWhy scala is not my ideal language and what I can do with this
Why scala is not my ideal language and what I can do with this
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applications
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
 
IDLs
IDLsIDLs
IDLs
 
R ext world/ useR! Kiev
R ext world/ useR!  KievR ext world/ useR!  Kiev
R ext world/ useR! Kiev
 
Jslab rssh: JS as language platform
Jslab rssh:  JS as language platformJslab rssh:  JS as language platform
Jslab rssh: JS as language platform
 
Behind OOD: domain modelling in post-OO world.
Behind OOD:  domain modelling in post-OO world.Behind OOD:  domain modelling in post-OO world.
Behind OOD: domain modelling in post-OO world.
 
scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Programming Languages: some news for the last N years
Programming Languages: some news for the last N yearsProgramming Languages: some news for the last N years
Programming Languages: some news for the last N years
 

Último

Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 

Último (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 

JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream

  • 1. JAVA8 / SCALA Difference points & innovation streams Ruslan Shevchenko. <ruslan@shevchenko.kiev.ua> https://github.com/rssh @rssh1
  • 2. JAVA / SCALA • Java & Scala significantly different • Exists innovations: scala => java & java=>scala • What language I must learn ? • All of them !
  • 3. SCALA JAVA8 public class Person { private String firstName; private String lastName; String getFirstName() { return firstName; } void setFirstName(String v) { firstName = v; } …………………. int hashCode() { if (firstName==null) { if (secondName==null) { return 0; } else { return secondName.hashCode(); } } else{ if (secondName==null) { } } } boolean equals() { …. } } case class Person ( firstName: String lastName: String )
  • 4. SCALA JAVA8 public class Person extends DTOBase { public String firstName; public String lastName; } case class Person ( firstName: String lastName: String )
  • 5. SCALA => JAVA Similar: lambda-expressions traits / default methods collections API with hight-order functions
  • 6. LAMBDA EXPRESSIONS list.sort((x,y)-> { int cmp = x.lastName.compareTo(y.lastName); return cmp!=0 ? cmp : x.firstName.compareTo(y.firstName) } list.sort((x,y) => { val cmp = x.lastName.compareTo(y.lastName) if (cmp!=0) cmp else x.firstName.compareTo(y.lastName) } Java Scala
  • 7. LAMBDA EXPRESSIONS var (maxFirstLen, maxSecondLen) = (0,0) list.foreach{ x => maxFirstLen = max(maxFirstLen, x.firstName.length) maxSecondLen = max(maxSecondLen, x.secondName.length) } Java Scala Closures can’t modify environment context …………………….
  • 8. TRAITS/DEFAULT METHODS trait AsyncInput[T] { def onReceive(acceptor:T=>()): Unit def read: Future[T] = { Promise p = Promise[T]() onReceive(p.complete(_)) p.future } } interface AsyncInput<T> { void onReceive(Acceptor<T> acceptor) default void read(): Future<T> { final CompletableFuture<T> promise = new CompletableFuture<>(); onReceive( x -> promise.complete(x) ); return promise; } } Scala Java
  • 9. TRAITS/DEFAULT METHODS trait LoggedAsyncInput[T] { this:AsyncInput => override def onReceive(acceptor:T => ()) = super.onReceive(x => { println(s“received:${x}”) acceptor(x) }) } Scala Java aspects ? …
  • 10. TRAITS/DEFAULT METHODS trait LoggedAsyncInput[T] { override def onReceive(acceptor:T => ()) = super.onReceive(x => { println(s“received:${x}”) acceptor(x) }) } Scala Java aspects ? … trait MyToString { override def toString = s”[${super.toString}]” }
  • 11. TRAITS/DEFAULT METHODS Java default interface: dispatch across class/interface hierarchy Scala traits building hierarchy with process of linearization
  • 12. STREAMING COLLECTIONS persons.stream().filter( x -> x.firstName.equals(”Jon”) ).collect(Collectors.toList()) persons.filter(_.firstName == “Jon”) Java Scala
  • 13. STREAMING COLLECTIONS persons.stream().filter( x -> x.firstName.equals(”Jon”) ).collect(Collectors.toList()) Java Reason - existing API Don’t want to mix old and new API in one Operation composition without reiterating.
  • 16. SQL ..??***8dc persons.filter(_.firstName === “Jon”) Scala (slick) Java (http://jinq.org) dbStream(em,Person.class).filter( x -> x.firstName.equals(“Jon”) ).list
  • 17. SQL (INSIDE ?) persons.filter(_.firstName === “Jon”).toList Scala (slick) TableQuery[Expr[Person]] Expr[String], Expr[StringConstant] => Expr[Boolean]
  • 18. SQL (INSIDE ?) persons.filter(_.firstName === “Jon”).toList Scala (slick) TableQuery[Expr[Person]] Expr[String], Expr[StringConstant] => Expr[Boolean] Query[Expr[T]], Expr[Boolean] => Query[Expr[T]] Query { … generateSql( .. ) }
  • 19. SQL (INSIDE) ..??***8dc Java (http://jinq.org) dbStream(em,Person.class).filter( x -> x.firstName.equals(“Jon”) ).list DbStream<Person> Person => Boolean
  • 20. SQL (INSIDE) ..??***8dc Java (http://jinq.org) dbStream(em,Person.class).filter( x -> x.firstName.equals(“Jon”) ).list Person => Boolean for sql generation we need: analyse bytecode symbolic interpretation collect trace generate sql // runtime-only, not very fast
  • 21. SQL (INSIDE) Java (http://jinq.org) // runtime-only, not very fast complex, state-of-the-art technology all work is in runtime unable to check function correctness in compile-time Scala (slick) relatively simple compile-time analysis, runtime generation verification in compile time
  • 22. JAVA => SCALA: SAM trait AsyncInputOutput[T] { def onReceive(acceptor:T=>()): Unit def onSend(generator: ()=>T): Unit } interface AsyncInputOutput<T> { void onReceive(Acceptor<T> acceptor) void onSend(Generator<T> generator) ……………… } Scala Java
  • 23. SAM • SAM-type =Type with Single Abstract Method • Method require SAM-type => we can pass lambda- expression to one. • In scala: • 2.11 — with -Xexperimental • 2.12 — by default
  • 24. SAM trait AsyncInputOutput[T] { Function1.class def onReceive(acceptor:T=>()): Unit Function1.class def onSend(generator: ()=>T): Unit } interface AsyncInputOutput<T> { Acceptor.class void onReceive(Acceptor<T> acceptor) Generator.class void onSend(Generator<T> generator) ……………… } Scala: JVM Java JIT inlining impossible Jit inlining is possible
  • 25. SCALA=>JAVA; JAVA=>SCALA • Java use ‘additional’ streaming API [not ideal, better than before] • Scala library can’t utilize SAM conversion [not ideal, better than before] • So, we have place for something 3-rd ? • Evolution: all ‘ideal’ shifts ….
  • 26. FUTURE EVOLUTION • 2 Groups • which will be integrated in java 9,10, 11, .. if exists. • [ FORTRAN 90 is object-oriented. Do you know this (?)] • case classes, type inheritance. • which represent essential different aspect, not present in java
  • 27. CASE CLASSES ..??***8dc case class Person(firstName: String, lastName: String) p match { case Person(“Jon”,”Galt” ) => “Hi, who are you ?” case Person(firstName, lastName) => s”Hi, ${firstName}, ${lastName}” case _ => “You are not person” } ML-style pattern matching, 1973 scala, kotlin, ceylon, swift
  • 28. FUTURE EVOLUTION • essential different aspect, not present in java: • internal DSL • flexible syntax • call by name • macros • Variance • strong typing • implicit context
  • 29. FLEXIBLE SYNTAX ..??***8dc def +++(x:Int, y:Int) = x*x*y*y 1 to 100 == 1.to(100) future(1) та future{1} def until(cond: =>Boolean)(body: => Unit): Unit
  • 30. CALL BY NAME ..??***8dc def dountil(cond: =>Boolean)(body: => Unit): Unit = { var quit = false; while(!quit) { body quit = !cond } } First introduced in Algol 68 var x = 0 dountil(x != 10)(x+=1)
  • 31. OWN SYNTAX ..??***8dc object Do { def apply(body: =>Unit) = new DoBody(body) } class DoBody(body: => Unit) { def until(cond: =>Boolean): Unit = { body; while(!cond) body } } Do { x = x+1 } until (x<10)
  • 32. BASIC DSL:) ..??***8dc object Lunar extends Baysick { def main(args:Array[String]) = { 10 PRINT "Welcome to Baysick Lunar Lander v0.9" 20 LET ('dist := 100) 30 LET ('v := 1) 40 LET ('fuel := 1000) 50 LET ('mass := 1000) 60 PRINT "You are drifting towards the moon." 70 PRINT "You must decide how much fuel to burn." 80 PRINT "To accelerate enter a positive number" 90 PRINT "To decelerate a negative" 100 PRINT "Distance " % 'dist % "km, " % "Velocity " % 'v % "km/s, " % "Fuel " % 'fuel 110 INPUT 'burn 120 IF ABS('burn) <= 'fuelTHEN 150 130 PRINT "You don't have that much fuel" 140 GOTO 100 ogus.me/2009/03/26/baysick-a-scala-dsl-implementing-basic/
  • 33. ..??***8dccollection.foreach(x => doSomething) ‘FOR’ SPECIAL SYNTAX ..??***8dcfor( x <- collection) doSomething = ..??***8dc for(x <- fun1 if (x.isGood); y <- fun2(x) ) yield z(x,y) = ..??***8dc fun1.withFilter(_.isGood). flatMap(x => fun2.map(y=>z(x,y)))
  • 34. ..??***8dccollection.foreach(x => doSomething) ‘FOR’ SPECIAL SYNTAX ..??***8dcfor( x <- collection) doSomething = ..??***8dc for(x <- collection) yield something = ..??***8dccollection.map( x => something)
  • 35. ‘FOR’ SPECIAL SYNTAX ..??***8dc = ..??**8dc for(r <- rows; c <- cell(r) ) …. rows.flatMap(r => cell.map(c =>….)) ..??***8dcfor(x <- c if p(x)) …. = ..??***8dcc.withFilter(x->p(x)) …
  • 36. ..??***8dccollection.foreach(x => doSomething) ‘FOR’ SPECIAL SYNTAX ..??***8dcfor( x <- collection) doSomething = ..??***8dc for(x <- fun1 if (x.isGood); y <- fun2(x) ) yield z(x,y) = ..??***8dc fun1.withFilter(_.isGood). flatMap(x => fun2.map(y=>z(x,y)))
  • 37. FOR-SYNTAX • own foreach: possible to use ‘for’ • ‘Monadic interfaces’ • //foreach, map, flatMap, withFilter • // scala-virtualized (not in standard) • define own function for all syntax constructions
  • 38. IMPLICIT implicit def f(x): y Use x as y add ‘own’ methods to existing classes pass context define type-guided expressions
  • 39. FUTURE: MONADIC ..??***8dc for( x <- Future{ calculate x }; y <- Future{ calculate y } ) yield x(x,y) Future[T] foreach — do something after competition map flatMap — future composition
  • 40. MACROS ..??***8dc object Log { def apply(msg: String): Unit = macro applyImpl def applyImpl(c: Context)(msg: c.Expr[String]):c.Expr[Unit] = { import c.universe._ val tree = q"""if (Log.enabled) { Log.log(${msg}) } """ c.Expr[Unit](tree) } Log(msg) if (Log.enabled) { Log.log(msg) }
  • 41. MACROS Reduce boilerplate code Fast code generation for HPC Deep AST transformations example: async
  • 42. ASYNC AS MACROS ..??***8dc async { val x = async{ long-running-code-x } val y = async{ long-running-code-y } val z = await(x) + await(y) } Rewritten as state machine without blocking Implemented as library (without language change) async: T => Future[T ] await: Future[T] =>T
  • 44. JAVA/SCALA • Java - stable domain, mapped to classes and objects. • Scala - in complex area, where new level of abstractions needed. • In the beginning of PL evolution, but totally new dimension
  • 45. THANKS FOR ATTENTION Ruslan Shevchenko <ruslan@shevchenko.kiev.ua> @rssh1 https://github.com/rssh