SlideShare a Scribd company logo
1 of 20
Download to read offline
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!

More Related Content

What's hot

Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Talk - Query monad
Talk - Query monad Talk - Query monad
Talk - Query monad Fabernovel
 
Swift internals
Swift internalsSwift internals
Swift internalsJung Kim
 
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)Hermann Hueck
 
Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)Swift 3.0 の新しい機能(のうちの9つ)
Swift 3.0 の新しい機能(のうちの9つ)Tomohiro Kumagai
 
Understanding static analysis php amsterdam 2018
Understanding static analysis   php amsterdam 2018Understanding static analysis   php amsterdam 2018
Understanding static analysis php amsterdam 2018Damien Seguy
 
Operators
OperatorsOperators
Operatorsvvpadhu
 
Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
From Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersFrom Functor Composition to Monad Transformers
From Functor Composition to Monad TransformersHermann Hueck
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJSunil OS
 
Interface
InterfaceInterface
Interfacevvpadhu
 
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 ExamplesGanesh Samarthyam
 

What's hot (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
 

Similar to ScalaFlavor4J

Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
Thinking Functionally with JavaScript
Thinking Functionally with JavaScriptThinking Functionally with JavaScript
Thinking Functionally with JavaScriptLuis Atencio
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetJose Perez
 
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 JVMRafael Winterhalter
 
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.pdfarjuntelecom26
 
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxNew folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docxcurwenmichaela
 
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 6Dmitry Soshnikov
 
함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게함수형사고 4장 열심히보다는현명하게
함수형사고 4장 열심히보다는현명하게박 민규
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageAnıl Sözeri
 
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-CAlexis Gallagher
 
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.docxandreecapon
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
ES6 and AngularAMD
ES6 and AngularAMDES6 and AngularAMD
ES6 and AngularAMDdhaval10690
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?Henri Tremblay
 

Similar to 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
 
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
 
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
OracleCode One 2018: Java 5, 6, 7, 8, 9, 10, 11: What Did You Miss?
 

More from Kazuhiro Sera

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...Kazuhiro Sera
 
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 #ScalaMatsuriKazuhiro Sera
 
Skinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライドSkinny Meetup Tokyo 2 日本語スライド
Skinny Meetup Tokyo 2 日本語スライドKazuhiro Sera
 
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarconSeasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarconKazuhiro Sera
 
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageekJava エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageekKazuhiro Sera
 
Future on Servlet #scala_ks
Future on Servlet #scala_ksFuture on Servlet #scala_ks
Future on Servlet #scala_ksKazuhiro Sera
 
Servlet と Future の関わり方 #scala_ks
Servlet と Future の関わり方 #scala_ksServlet と Future の関わり方 #scala_ks
Servlet と Future の関わり方 #scala_ksKazuhiro Sera
 
マイクロサービス運用の所感 #m3dev
マイクロサービス運用の所感 #m3devマイクロサービス運用の所感 #m3dev
マイクロサービス運用の所感 #m3devKazuhiro Sera
 
Scala が支える医療系ウェブサービス #jissenscala
Scala が支える医療系ウェブサービス #jissenscalaScala が支える医療系ウェブサービス #jissenscala
Scala が支える医療系ウェブサービス #jissenscalaKazuhiro Sera
 
Scala on Rails #rakutentech
Scala on Rails #rakutentechScala on Rails #rakutentech
Scala on Rails #rakutentechKazuhiro Sera
 
Solid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaSolid And Sustainable Development in Scala
Solid And Sustainable Development in ScalaKazuhiro Sera
 
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_cccKazuhiro Sera
 
[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_r24Kazuhiro Sera
 
Skinny Framework 1.0.0
Skinny Framework 1.0.0Skinny Framework 1.0.0
Skinny Framework 1.0.0Kazuhiro Sera
 
Skinny Framework Progress Situation
Skinny Framework Progress SituationSkinny Framework Progress Situation
Skinny Framework Progress SituationKazuhiro Sera
 
Skinny Framework 進捗どうですか? #fud_scala
Skinny Framework 進捗どうですか? #fud_scalaSkinny Framework 進捗どうですか? #fud_scala
Skinny Framework 進捗どうですか? #fud_scalaKazuhiro Sera
 
テストの運用について #m3dev
テストの運用について #m3devテストの運用について #m3dev
テストの運用について #m3devKazuhiro Sera
 
めんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaめんどくさくない Scala #kwkni_scala
めんどくさくない Scala #kwkni_scalaKazuhiro Sera
 
歌舞伎座.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_techKazuhiro Sera
 

More from 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
 

Recently uploaded

RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 

Recently uploaded (20)

RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 

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!