SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
ScalaFlavor4J
- Scala flavored API in Java -

    Kazuhiro Sera @seratch
What’s this?

• github.com/m3dev/scalaflavor4j
• A pure Java library
• NOT a wrapper of scala-library.jar
• Function, Seq, Range, Option, Map, ParSeq...
• Already used by some apps at M3, Inc.
Motivation
• “For fun”
• To get along with legacy Java systems
• Help co-workers ease into Scala (showing
  them that Scala has a lot of useful APIs)
• Might be useful as a Scala educational tool
  for Java programmers
Function
// val getLength = (str: String) => if (str == null) 0 else str.length
// val len = getLength(“foo”)

import com.m3.scalaflavor4j.*;
F1<String,Integer> getLength = new F1<String,Integer>() {
  public Integer _(String str) { // apply method definition
    return str == null ? 0 : str.length();
  }
};
final int len = getLength.apply(“foo”); // -> 3
final int len = getLength._(“foo”); // -> 3
Option
// val opt = Option(“something”)

Option<String> opt = Option._(“something”);
opt.isDefined(); // -> true
opt.getOrNull(); // -> “something”
Option<String> none = Option._(null);
none.getOrElse(“”); // -> “”

opt.map(new F1<String,String>() { ... }) // apply F1 if Some
 .getOrElse(new F0<String>() { ... }); // apply F0 if None
Example(Option)
class UserService {
  public User findById(String id) { return DB.findUserById(id); }
}
User user = userService.findById(“123”)); // user might be null
↓
class UserService {
  public Option<User> findById(String id) {
    return Option._(DB.findUserById(id));
  } // Explicitly state that User might be null
}
Seq

// val seq = Seq(1,2,3,4,5)

Seq<Integer> seq = Seq._(1,2,3,4,5)

import java.util.*;
List<Integer> javaList = Arrays.asList(1,2,3,4,5);
Seq<Integer> seq = Seq._(javaList);
javaList = seq.toList();
#map(F1)

// val values = Seq(1,2,3,4,5) map { i => i *i }

Seq<Integer> values = Seq._(1,2,3,4,5).map(
   new F1<Integer, Integer>() {
     public Integer _(Integer i) { return i * i; }
   }
);
// -> 1,4,9,16,25
#flatMap(F1)
// val values = Seq(1,2,3) flatMap { i => 1 to i }

Seq<Integer> values = Seq._(1,2,3).flatMap(
   new F1<Integer, CollectionLike<Integer>>() {
     public Seq<Integer> _(Integer i) {
       return SInt._(1).to(i);
     }
   }
);
// -> 1,1,2,1,2,3
// * CollectionLike accepts Seq and Option
#filter(F1)
// val values = Seq(1,2,3,4,5) filter { i => i > 1 }

Seq<Integer> values = Seq._(1,2,3,4,5).filter(
   new PredicateF1<Integer>() {
     public Boolean _(Integer i) { return i > 1; }
   }
);
// -> 3,4,5

// * PredicatedF1<A> is just an alias of F1<A,Boolean>
#foldLeft(F2)
// val values = Seq(1,2,3,4,5).foldLeft(0){ (z,i) => z + i }

Seq<Integer> values = Seq._(1,2,3,4,5).foldLeft(
   new FoldLeftF2<Integer,Integer>() {
     public Integer _(Integer z, Integer i) { return z + i; }
   }
);
// ->15

// * FoldLeft2<A,B> is just an alias of F2<A,B,A>
#foreach(VoidF1)

// Seq(1,2,3) foreach { i => println(i) }

Seq<Integer> values = Seq._(1,2,3).foreach(
   new VoidF1<Integer>() {
     public void _(Integer i) { System.out.println(i); }
   }
);
// -> Displayed “1” “2” “3”
Example(Seq)
List<Integer> input = Arrays.asList(3,2,5,0,4,1);
List<Integer> result = new ArrayList<Integer>();
for ( Integer i : input ) {
  if ( i != null && i > 2 ) { result.add(i * i); }
}
↓
Seq._(input).filter(new PredicateF1<Integer>() {
  public Boolean _(Integer i) { return i != null && i >2; }
}).map(new F1<Integer, Integer>() {
  public Integer _(Integer i) { return i * i; }
}).toList(); // No mutable state, Separation
ParSeq
// val values = (1 to 100).par.map { i => i *i }

Seq<Integer> values = SInt._(1).to(100).par().map(
   new F1<Integer, Integer>() {
     public Integer _(Integer i) {
       System.out.println(Thread.currentThread.getId());
       return i * i;
     } // Using Fork/Join framework(Available on JDK6)
   }
);
// -> 1,4,9,16,25
Range

// val range: Seq[Int] = 1 to 10
// val range: Seq[Long] = 1L to 10L
Seq<Integer> range = SInt._(1).to(10);
Seq<Long> range = SLong._(1).until(11);

for(int i=0; i<10; i++) { ... }
↓
SInt._(0).until(10).foreach { ... }
Map

// val map = Map(1 -> “foo”, 2 -> “bar”)

import java.util.*;
Map<Integer, String> javaMap = new HashMap<>();
SMap<Integer, String> map = SMap._(javaMap);

// map,flatMap,filter,foreach, etc. are available
map.filter(new PredicateF1<Tuple2<Integer,String>>() {...});
map.map(new F1<Tuple2<Integer,String>>() {...});
ConcurrentOps
// import scala.concurrent.ops._
// spawn { println(“On a different thread!”) }

new Thread(new Runnable() { public void run() {
  System.out.println(“On a different thread!”);
}}).start();
↓
import static com.m3.scalaflavor4j.ConcurrentOps.*;
spawn(new VoidF0() { public void _() {
  System.out.println(“On a different thread!”);
}}); // using Fork/Join
ExceptionControl
// import scala.util.control.Exception._
// val result = catching(classOf[Exception]) withApply {
// (t: Throwable) => “ng”;
// } apply { “ok” }

import static com.m3.scalaflavor4j.ExceptionControl.*;
String result = catching(Exception.class)
 .withApply(new F1<Throwable>() {
   public String _(Throwable t) { return “ng”; } })
 .apply(new F0<String>() {
   public String _() { return “ok”; } });
Example(catching)
String result;
try { result = “ok”;
} catch (AException ae) { result = “ng”;
} catch (BException be) { result = “ng”; }
↓
String result = catching(AException.class, BException.class)
  .withApply(new F1<Throwable>() {
    public String _(Throwable t) { return “ng”; } })
  .apply(new F0<String>() {
    public String _() { return “ok”; }
  });
andThen(You)

• More information -> https://github.com/
  m3dev/scalaflavor4j
• Feature requests welcome
• Pull requests welcome
• Let’s enjoy Java with ScalaFlavor4J!

Contenu connexe

Tendances

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
Alok Kumar
 

Tendances (17)

Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad
 
Swift internals
Swift internalsSwift internals
Swift internals
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Collection Core Concept
Collection Core ConceptCollection Core Concept
Collection Core Concept
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)
 
Understanding static analysis php amsterdam 2018
Understanding static analysis   php amsterdam 2018Understanding static analysis   php amsterdam 2018
Understanding static analysis php amsterdam 2018
 
Swift 2
Swift 2Swift 2
Swift 2
 
Operators
OperatorsOperators
Operators
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad Transformers
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
Interface
InterfaceInterface
Interface
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 

Similaire à ScalaFlavor4J

package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
arjuntelecom26
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
curwenmichaela
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
andreecapon
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 

Similaire à ScalaFlavor4J (20)

Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015
 
Javascript
JavascriptJavascript
Javascript
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScript
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docxMETA-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
ES6 and AngularAMD
ES6 and AngularAMDES6 and AngularAMD
ES6 and AngularAMD
 

Plus de Kazuhiro Sera

Future on Servlet #scala_ks
Future on Servlet #scala_ksFuture on Servlet #scala_ks
Future on Servlet #scala_ks
Kazuhiro Sera
 
テストの運用について #m3dev
テストの運用について #m3devテストの運用について #m3dev
テストの運用について #m3dev
Kazuhiro Sera
 

Plus de Kazuhiro Sera (20)

All I learned while working on a Scala OSS project for over six years #ScalaM...
All I learned while working on a Scala OSS project for over six years #ScalaM...All I learned while working on a Scala OSS project for over six years #ScalaM...
All I learned while working on a Scala OSS project for over six years #ScalaM...
 
Contributing to Scala OSS from East Asia #ScalaMatsuri
 Contributing to Scala OSS from East Asia #ScalaMatsuri Contributing to Scala OSS from East Asia #ScalaMatsuri
Contributing to Scala OSS from East Asia #ScalaMatsuri
 
Skinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライドSkinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライド
 
Skinny 2 Update
Skinny 2 UpdateSkinny 2 Update
Skinny 2 Update
 
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarconSeasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
 
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageekJava エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
 
Future on Servlet #scala_ks
Future on Servlet #scala_ksFuture on Servlet #scala_ks
Future on Servlet #scala_ks
 
Servlet と Future の関わり方 #scala_ks
Servlet と Future の関わり方 #scala_ksServlet と Future の関わり方 #scala_ks
Servlet と Future の関わり方 #scala_ks
 
マイクロサービス運用の所感 #m3dev
マイクロサービス運用の所感 #m3devマイクロサービス運用の所感 #m3dev
マイクロサービス運用の所感 #m3dev
 
Scala が支える医療系ウェブサービス #jissenscala
Scala が支える医療系ウェブサービス #jissenscalaScala が支える医療系ウェブサービス #jissenscala
Scala が支える医療系ウェブサービス #jissenscala
 
Scala on Rails #rakutentech
Scala on Rails #rakutentechScala on Rails #rakutentech
Scala on Rails #rakutentech
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in Scala
 
Beginning Scala with Skinny Framework #jjug_ccc
Beginning Scala with Skinny Framework #jjug_cccBeginning Scala with Skinny Framework #jjug_ccc
Beginning Scala with Skinny Framework #jjug_ccc
 
[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24
[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24
[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24
 
Skinny Framework 1.0.0
Skinny Framework 1.0.0Skinny Framework 1.0.0
Skinny Framework 1.0.0
 
Skinny Framework Progress Situation
Skinny Framework Progress SituationSkinny Framework Progress Situation
Skinny Framework Progress Situation
 
Skinny Framework 進捗どうですか? #fud_scala
Skinny Framework 進捗どうですか? #fud_scalaSkinny Framework 進捗どうですか? #fud_scala
Skinny Framework 進捗どうですか? #fud_scala
 
テストの運用について #m3dev
テストの運用について #m3devテストの運用について #m3dev
テストの運用について #m3dev
 
めんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaめんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scala
 
歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech
歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech
歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
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, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 

ScalaFlavor4J

  • 1. ScalaFlavor4J - Scala flavored API in Java - Kazuhiro Sera @seratch
  • 2. What’s this? • github.com/m3dev/scalaflavor4j • A pure Java library • NOT a wrapper of scala-library.jar • Function, Seq, Range, Option, Map, ParSeq... • Already used by some apps at M3, Inc.
  • 3. Motivation • “For fun” • To get along with legacy Java systems • Help co-workers ease into Scala (showing them that Scala has a lot of useful APIs) • Might be useful as a Scala educational tool for Java programmers
  • 4. Function // val getLength = (str: String) => if (str == null) 0 else str.length // val len = getLength(“foo”) import com.m3.scalaflavor4j.*; F1<String,Integer> getLength = new F1<String,Integer>() { public Integer _(String str) { // apply method definition return str == null ? 0 : str.length(); } }; final int len = getLength.apply(“foo”); // -> 3 final int len = getLength._(“foo”); // -> 3
  • 5. Option // val opt = Option(“something”) Option<String> opt = Option._(“something”); opt.isDefined(); // -> true opt.getOrNull(); // -> “something” Option<String> none = Option._(null); none.getOrElse(“”); // -> “” opt.map(new F1<String,String>() { ... }) // apply F1 if Some .getOrElse(new F0<String>() { ... }); // apply F0 if None
  • 6. Example(Option) class UserService { public User findById(String id) { return DB.findUserById(id); } } User user = userService.findById(“123”)); // user might be null ↓ class UserService { public Option<User> findById(String id) { return Option._(DB.findUserById(id)); } // Explicitly state that User might be null }
  • 7. Seq // val seq = Seq(1,2,3,4,5) Seq<Integer> seq = Seq._(1,2,3,4,5) import java.util.*; List<Integer> javaList = Arrays.asList(1,2,3,4,5); Seq<Integer> seq = Seq._(javaList); javaList = seq.toList();
  • 8. #map(F1) // val values = Seq(1,2,3,4,5) map { i => i *i } Seq<Integer> values = Seq._(1,2,3,4,5).map( new F1<Integer, Integer>() { public Integer _(Integer i) { return i * i; } } ); // -> 1,4,9,16,25
  • 9. #flatMap(F1) // val values = Seq(1,2,3) flatMap { i => 1 to i } Seq<Integer> values = Seq._(1,2,3).flatMap( new F1<Integer, CollectionLike<Integer>>() { public Seq<Integer> _(Integer i) { return SInt._(1).to(i); } } ); // -> 1,1,2,1,2,3 // * CollectionLike accepts Seq and Option
  • 10. #filter(F1) // val values = Seq(1,2,3,4,5) filter { i => i > 1 } Seq<Integer> values = Seq._(1,2,3,4,5).filter( new PredicateF1<Integer>() { public Boolean _(Integer i) { return i > 1; } } ); // -> 3,4,5 // * PredicatedF1<A> is just an alias of F1<A,Boolean>
  • 11. #foldLeft(F2) // val values = Seq(1,2,3,4,5).foldLeft(0){ (z,i) => z + i } Seq<Integer> values = Seq._(1,2,3,4,5).foldLeft( new FoldLeftF2<Integer,Integer>() { public Integer _(Integer z, Integer i) { return z + i; } } ); // ->15 // * FoldLeft2<A,B> is just an alias of F2<A,B,A>
  • 12. #foreach(VoidF1) // Seq(1,2,3) foreach { i => println(i) } Seq<Integer> values = Seq._(1,2,3).foreach( new VoidF1<Integer>() { public void _(Integer i) { System.out.println(i); } } ); // -> Displayed “1” “2” “3”
  • 13. Example(Seq) List<Integer> input = Arrays.asList(3,2,5,0,4,1); List<Integer> result = new ArrayList<Integer>(); for ( Integer i : input ) { if ( i != null && i > 2 ) { result.add(i * i); } } ↓ Seq._(input).filter(new PredicateF1<Integer>() { public Boolean _(Integer i) { return i != null && i >2; } }).map(new F1<Integer, Integer>() { public Integer _(Integer i) { return i * i; } }).toList(); // No mutable state, Separation
  • 14. ParSeq // val values = (1 to 100).par.map { i => i *i } Seq<Integer> values = SInt._(1).to(100).par().map( new F1<Integer, Integer>() { public Integer _(Integer i) { System.out.println(Thread.currentThread.getId()); return i * i; } // Using Fork/Join framework(Available on JDK6) } ); // -> 1,4,9,16,25
  • 15. Range // val range: Seq[Int] = 1 to 10 // val range: Seq[Long] = 1L to 10L Seq<Integer> range = SInt._(1).to(10); Seq<Long> range = SLong._(1).until(11); for(int i=0; i<10; i++) { ... } ↓ SInt._(0).until(10).foreach { ... }
  • 16. Map // val map = Map(1 -> “foo”, 2 -> “bar”) import java.util.*; Map<Integer, String> javaMap = new HashMap<>(); SMap<Integer, String> map = SMap._(javaMap); // map,flatMap,filter,foreach, etc. are available map.filter(new PredicateF1<Tuple2<Integer,String>>() {...}); map.map(new F1<Tuple2<Integer,String>>() {...});
  • 17. ConcurrentOps // import scala.concurrent.ops._ // spawn { println(“On a different thread!”) } new Thread(new Runnable() { public void run() { System.out.println(“On a different thread!”); }}).start(); ↓ import static com.m3.scalaflavor4j.ConcurrentOps.*; spawn(new VoidF0() { public void _() { System.out.println(“On a different thread!”); }}); // using Fork/Join
  • 18. ExceptionControl // import scala.util.control.Exception._ // val result = catching(classOf[Exception]) withApply { // (t: Throwable) => “ng”; // } apply { “ok” } import static com.m3.scalaflavor4j.ExceptionControl.*; String result = catching(Exception.class) .withApply(new F1<Throwable>() { public String _(Throwable t) { return “ng”; } }) .apply(new F0<String>() { public String _() { return “ok”; } });
  • 19. Example(catching) String result; try { result = “ok”; } catch (AException ae) { result = “ng”; } catch (BException be) { result = “ng”; } ↓ String result = catching(AException.class, BException.class) .withApply(new F1<Throwable>() { public String _(Throwable t) { return “ng”; } }) .apply(new F0<String>() { public String _() { return “ok”; } });
  • 20. andThen(You) • More information -> https://github.com/ m3dev/scalaflavor4j • Feature requests welcome • Pull requests welcome • Let’s enjoy Java with ScalaFlavor4J!