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

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
 

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

Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Impress Your Friends with EcmaScript 2015
Impress Your Friends with EcmaScript 2015Lukas Ruebbelke
 
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.pdfamazing2001
 
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
 

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

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
 

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

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
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 RobisonAnna Loughnan Colquhoun
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
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 Scriptwesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
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
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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!