SlideShare uma empresa Scribd logo
1 de 69
Baixar para ler offline
Comparing JVM languages
José Manuel Ortega Candel | @jmortegac
26-27 June 2015
INDEX
Functional programming and closures2
Language classification1
Java 8 new features3
Scala, Groovy, Kotlin, Clojure and Ceylon4
Advantages and drawbacks5
Comparing features6
Language classification
FUNCTIONAL NOT FUNCTIONAL
STATIC
DYNAMIC
Functional programming
•Data structure persistent and immutable
•Closures
•Higher order functions
•Pass functions to functions as parameter
•Create functions within functions
•Return functions from other functions
•Functions as first class values
Closures
•Reduce amount of “boiler plate” code
•Eliminate the boilerplate code of anonymous
inner classes
•Allow the use of idiomatic functional
programming code
•Allow the creation of custom control structures
•In Java 8 closures are just syntactic sugar for
defining anonymous inner classes
Java 8 new
features
 Lambda expressions
 Closures
 Streams
 Enhaced collections
 Processing data in parallel
 Pattern Filter-Map-Reduce
 Annotations types
 Methods References
(String s)-> System.out.println(s)
System.out::println
Streams
Filter-Map-Reduce
Book book=new Book(123455,"Beginning Java 8");
Book book1=new Book(3232332,"Java 8 Advanced");
Book book2=new Book(43434343,"Groovy Advanced");
List<Book> books=Arrays.asList(book,book1,book2);
Predicate<Book> condition=(it) -> it.getTitle().contains("Java");
String jsonFormat=books
.stream()
.filter(condition)
.map(Book::toJSON)
.collect(Collectors.joining(", "));
[{isbn:123455,title:'Beginning Java 8'}, {isbn:3232332,title:'Java 8 Advanced'}]
Parallel Streams
List myList = ..
Stream stream = myList.stream();
Stream parallelStream = myList.parallelStream();
Stream parallel = stream.parallel();
•Streams are sequential by default
•With Parallel you can optimize number of threads
•More efficient with bigger collections
Sequential vs Parallel
books.parallelStream().filter((it) -> it.getTitle().contains("Java")).
forEach((it)->System.out.println(it+" "+Thread.currentThread()));
Book{isbn=3232332, title='Java 8 Advanced'} Thread[main,5,main]
Book{isbn=123455, title='Beginning Java 8'} Thread[main,5,main]
books.stream().filter((it) -> it.getTitle().contains("Java")).
forEach((it)->System.out.println(it+" "+Thread.currentThread()));
Book{isbn=3232332, title='Java 8 Advanced'} Thread[main,5,main]
Book{isbn=123455, title='Beginning Java 8'} Thread[ForkJoinPool.commonPool-
worker-2,5,main]
Scala
Combines the paradigms of functional
programming and object-oriented
Statically typed
No types primitives like Java
Everything is an Object, including functions
Performance equivalent to Java
Scala features
Pattern matching
Closures,lambdas,anonymous functions
Traits and mixins for multiple inheritance
Operator overloading
Support Data Paralell like Java 8
Concurrency models(Akka,actors)
Inmutable and mutable data structures
Scala examples
def factorial(n : Int): Int = n match{
case 0 => 1
case x if x >0 => factorial(n-1) *n
}
val languages = List("Scala", "Groovy", "Clojure", "Kotlin")
val headList = languages.head // Scala
val tailList = languages.tail; //List( "Groovy", "Clojure", "Kotlin")
val empty = languages.isEmpty //false
def orderList(xs: List[String]): List[String] =
if (xs.isEmpty) Nil
else insert(xs.head, isort(xs.tail)
@BeanProperty
Annotation which is read by the Scala
compiler to generate getter and setter
class Bean {
@scala.reflect.BeanProperty
var name: String
}
val someNumbers = List(-11, -10, -5, 0, 5, 10)
someNumbers.filter((x) => x > 0)
someNumbers.filter(_ > 0)
List[Int] = List(5, 10)
scala.collection.immutable
Inmutability in Scala
scala> var languages = Set("Scala", "Kotlin")
languages : scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Kotlin)
scala> languages += "Clojure"
scala> languages
res: scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Kotlin, Clojure)
scala> languages -= " Kotlin "
scala> languages
res: scala.collection.immutable.Set[java.lang.String] =
Set(Scala, Clojure)
• You can add elements in a inmutable collection
Java 8 vs Scala
Java 8 vs Scala streams
bookList.parallelStream().filter(b -> b.title.equals(”Clojure”))
.collect(Collectors.toList())
bookList.par.filter(_.title == “Clojure”)
bookList.par.filter( b =>b.title == “Clojure”)
val bookFilter = bookList.par.filter(_.title.contains("Groovy"))
.foreach{i=> println(Thread.currentThread) }
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-5,5,main]
Kotlin
Object-oriented with functional elements
Developed by JetBrains
Statically typed like Scala
Smarts casts
Elvis operator(?) for checking null like Groovy
Type inference
100 % interoperability with Java
Kotlin syntax & rules
Inmutable/Mutable variables
No new keyword for create objects
No primitive types
No static members
Primary constructors
No fields, just properties
By default, all classes are final
Kotlin
Smart casts Maps
val languages = mapOf("Java" to "Gosling",
"Scala" to "Odersky","Groovy" to "Strachan")
for((language,author) in languages){
println("$author made $language")
}
fun eval(e: Expr): Double = when (e) {
is Num-> e.value.toDouble()
is Sum -> eval(e.left) + eval(e.right)
else ->
throw IllegalArgumentException("Unknown
expression")
}
val mapLanguages = hashMapOf<String, String>()
mapLanguages.put("Java", "Gosling")
mapLanguages.put("Scala", "Odersky")
for ((key, value) in mapLanguages) {
println("key = $key, value = $value")
}
fun patternMatching(x:Any) {
when (x) {
is Int -> print(x)
is List<*> ->{print(x.count())}
is String -> print(x.length())
!is Number -> print("Not even a number")
else -> print("can't do anything")
}
}
Kotlin
Operator overloading Default & name arguments
println(product(2))
println(product(2,3))
println(format(text="kotlin"))
println(format(text="kotlin", upperCase= true))
2
6
kotlin
KOTLIN
fun product(a:Int,b:Int=1):Int{
return a.times(b);
}
fun format(text:String,upperCase:Boolean=
false):String {
return if (upperCase) text.toUpperCase() else text
}
Kotlin
Iterators
fun iterateOverCollection(collection: Collection<Int>) {
for (element in collection) {}
}
fun iterateOverString() {
for (c in "abcd") {}
"abcd".iterator()
}
fun iteratingOverMap(map: Map<Int, String>) {
for ((key, value) in map) {}
}
Kotlin
Data classes
 Data annotation changes behavior of hashCode, equals, toString functions
public class Book (var isbn:Int, var title:String)
fun main(args: Array<String>) {
//Books
val book = Book(123456, "Beginning Kotlin")
val book2 = Book(123456, "Beginning Kotlin")
println(book);
println(book.hashCode());
println(book2.hashCode());
println(book.equals(book2));
if (book == book2)
println("Same Book");
if (book != book2)
println("Diferent Book");
}
books.Book@2a84aee7
713338599
168423058
false
Diferent Book
data public class Book (var isbn:Int, var title:String)
fun main(args: Array<String>) {
//Books
val book = Book(123456, "Beginning Kotlin")
val book2 = Book(123456, "Beginning Kotlin")
println(book);
println(book.hashCode());
println(book2.hashCode());
println(book.equals(book2));
if (book == book2)
println("Same Book");
if (book != book2)
println("Diferent Book");
Book(isbn=123456,
title=Beginning Kotlin)
1848623012
1848623012
true
Same Book
Kotlin
Classes constructor
• It is not necessary define a constructor like in Java
• You can use the class definition to pass the properties and
default values
data public class Book (var isbn:Int, var title:String="My Default Book")
fun main(args: Array<String>) {
val book = Book(123456)
println(book.title);
}
Kotlin
Higher order functions
• Lambda expressions
• it implicit parameter
val filter = books filter({ b: Book -> b.title.contains(“Kotlin") })
val book = Book(123455, "Beginning Java 8")
val book1 = Book(3232332, "Java 8 Advanced")
val book2 = Book(43434343, “Kotlin Advanced")
val books = Arrays.asList(book, book1,book2)
Filter[Book(isbn=43434343, title=Kotlin Advanced)]
val filter = books filter({ it.contains(“Kotlin") })
Kotlin collections
val listInmutable
=listOf("Java","Kotlin","Groovy","Scala")
val listMutable=ArrayList<String>()
listMutable.add("Java")
listMutable.add("Kotlin")
Kotlin vs Java list iterate
for ((index,element) in list.withIndex()) {
println(“$index$element”);
}
int index=0
for (String element:list) {
System.out.println(index+””+element);
index++
}
Kotlin smart cast vs Java
if (expr is Number) {
println(expr.getValue());
//expr is automatically cast to Number
}
if (expr instanceof Number) {
System.out.println((Number)expr).getValue());
}
Kotlin vs Java types
inference
val longJavaClassName = LongJavaClassName()
LongJavaClassName longJavaClassName =new LongJavaClassName()
Groovy
 Java supercharged(syntactic sugar)
 Object oriented and dynamic language
 Optional typing like Scala and Kotlin
 All type checking is at run time
 It reduces Java boilerplate code including no
semi colons, no getters/setters, type
inference, null safety, elvis operators
Groovy
 Closures with lambda
or it implicit parameter
def upper = { s-> s.toUpperCase()}
def upper = {it.toUpperCase()}
 Collections
def languages = ["Java":”James
Gosling”, "Scala":”Martin Odersky”,
"Clojure":”Rich Hickey”,
"Ceylon":”Gavin King”,
"Groovy":”James Strachan”]
languages.each { entry -> println}
languages.each { k,v -> println}
 Methods as closures with .& operator
def object
object = 2
object = true
object = [1,2,3]
 Optional typing
Groovy
 @Memoized annotation  @Inmutable annotation
@Memoized
def BigInteger fibRecursiveMemoized(n) {
if (n<2) return 1
else return fibRecursiveMemoized(n-1) +
fibRecursiveMemoized(n-2)
}
TimeIt.code{println(fibonnaci.fibRecursive(40))}
TimeIt.code{println(fibonnaci.fibRecursiveMemoized(40))}
165580141
Time taken 42.083165464 seconds
165580141
Time taken 0.061408655 seconds //with memoize
import groovy.transform.Immutable
@Immutable class Language {
String title;
Long isbn;
}
def l1 = new Language (title:'Beginning Groovy',isbn:100)
def l2 = new Language (title:'Groovy advanced',isbn:200)
l1.title = 'Groovy for dummies'
// Should fail with groovy.lang.ReadOnlyPropertyException
Groovy
 Time execution
class TimeIt {
def static code(codeBlock){
def start = System.nanoTime()
try{
codeBlock()
}finally{
def end = System.nanoTime()
println "Time taken ${(end-start)/1e9} seconds"
}
}
}
Groovy
 Parsing and creating XML
Groovy
Advantages Disadvantages
Java Collections Non-lazy evaluation
Closures
(like Lambda expressions in Java 8)
It's performance isn't great
(but it's improving)
Filter – Map – Reduce in streams
Easy interoperability with Java
Static and dynamic typing
@TypeChecked
@CompileStatic
Metaprogramming
Java Groovy
def languages = ["Java", "Scala", "Clojure",
"Kotlin", "Ceylon","Groovy"]
def filter = languages.stream()
.findAll { it.size()>5 }
.collect { it.toUpperCase()}
.first()
List<String> languages = Arrays.asList("Java",
"Scala", "Clojure", "Kotlin","Ceylon","Groovy");
Optional<String> bookFiltered = languages.stream()
.filter(s -> s.length()>5 )
.map(s -> s.toUpperCase())
.findFirst();
Clojure
Pure functional language
JVM language based in Lisp
Not Object Oriented
Dynamically typed
All data structure including list ,vectors, maps,
sequences, collections, are inmutable and fully
persistent
The main data structure is the list
The key is the use of High Order Functions
Clojure
Alternate implementations in functions
(defn square-or-multiply
"squares a single argument, multiplies two arguments"
([] 0) # without arguments
([x] (* x x)) # one argument
([x y] (* x y))) # two arguments
List operations
(first '(:scala :groovy :clojure))return scala
(rest '(:scala :groovy :clojure))return all elements excepts the first
(cons :kotlin '(:scala :groovy :clojure))add kotlin to head in the list
Clojure
Sequences
(defn count-down [n]
(if (<= n 0)
'(0)
(cons n (lazy-seq (count-down (dec n))))))
Filter – Map - Reduce
(filter integer? [1 2.71 3.14 5 42]) => (1 5 42)
(map (fn [n] (* n n)) [1 2 3 4 5]) => (1 4 9 16 25)
(reduce + [1 2 3 4]) => 10
user=> (count-down 8)
(8 7 6 5 4 3 2 1 0)
Clojure
Records
(defrecord Book [isbn title])
(def bookList [(Book. 432423 "Clojure")(Book. 534243 "Kotlin")
(Book. 432424 "Groovy")])
(println "count bookList "(count bookList))
(dorun (for [item bookList]
(println (:title item)(:isbn item))))
(println (filter #(= "Clojure" (get % :title)) bookList))
count bookList 3
Clojure 432423
Kotlin 534243
Groovy 432424
(#user.Book{:isbn 432423, :title
Clojure})
(defrecord Object [prop1 propn])
Clojure
Recursive functions with trampoline and memoize
(defn factorial ([x] (trampoline (factorial (dec x) x)))
([x a] (if (<= x 1) a #(factorial (dec x) (*' x a)))))
(def fibonaci
(memoize (fn [n]
(if (< n 2)
n
(+ (fibonaci (dec n))
(fibonaci (dec (dec n))))))))
(time(println (factorial 20)))
(time(println (fibonaci 30)))
"Elapsed time: 0.692549 msecs"
832040
"Elapsed time: 1.263175 msecs"
"Elapsed time: 24.574218 msecs"
832040
"Elapsed time: 118.678434 msecs"
2432902008176640000
Clojure
Advantages Disadvantages
Very simple Not Object oriented
The language has little elements
compared with other languages
Difficult to decipher stacktraces and errors
Excellent concurrency support Requires a new way to solve problems
Easy interoperability with java There are no variables
Powerful language features
(macros,protocols)
Thre is no inheritance concept
Clojure programs run very quickly No mecanism for avoid NullPointerException
JVM is highly optimized
Clojure vs Java
Code reducing
(defn blank [str]
(every#? (Character/isWhitespace %)
str))
public class StringUtils {
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)))) {
return true;
}}
return false;
}}
Ceylon
Is very similar to Java, reducing verbosity
Object oriented with functional features
Strong static typing with type inference
Explicit module system
 Comparing with Java
 Eliminates static, public, protected, private
 Add new modifiers like variable, shared, local
 Shared is used for make visibility outside in other
modules(like public in Java)
 Arrays are replaced by sequences
Ceylon
Sequence languages = Sequence("Java",
"Groovy","Clojure","Kotlin");
//Check if the sequence is empty
if(nonempty languages){
String? firstElementValue = languages.value(1);
String? firstElement = languages.first;
}
Sequence more =
join(languages,Sequence("Ceylon","Scala"));
Sequences Generics & Union types
Iterable<String|Boolean> list =
{“string”,true,false}
ArrayList<Integer|Float> list =
ArrayList<Integer|Float>
(1, 2, 1.0, 2.0)
Comparing featues
•Reducing verbosity
•Variables definition
•Null-safety
•Optional types
•Lambdas
•Pattern matching
•Traits
•Java interoperability
Reducing Java verbosity
Reducing Boilerplate Code
class MyClass{
private int index;
private String name;
public MyClass(int index, String name){
this.index = index;
this.name = name;
}
}
case class MyClass(index: Int, name: String)
public class MyClass(var index:Integer,var name:String){
}
class MyClass {
int index
String name
}
class MyClass(index,name) {
shared Integer index;
shared String name;
}
(defstruct MyClass :index :name)
Variables definition
• In Kotlin and Scala you can define 2 types
• var myMutableVariable
• val myInmutableVariable
• In Ceylon we have variable modifier for mutable
variable Integer count=0;
count++; //OK
Integer count=0;
count++;//ERROR
val name: Type = initializer // final “variable”
var name: Type = initializer // mutable variable
Null-safety
•Operator ? used in Kotlin,Groovy,Ceylon
•Avoid NullPointerException
var b : String? = "b"
b = null // valid null assignment
val l = b?.length()
Elvis Operator(?:) and Safe navigation (?.)
def displayName = user.name ? user.name : "Anonymous“
def streetName = user?.address?.street
String? argument = process.arguments.first;
if (exists argument) { //checking null values
}
Optional Types
Optional<Object> optional = findObject(id);
//check if Optional object has value
if (optional.isPresent()) {
System.out.println(optional.get());
}
Type safe Option[T] in Scala
New class java.util.Optional
Optional Type in Scala
private val languages = Map(1 -> Language(1, "Java", Some("Gosling")),
2 -> Language(2, "Scala", Some("Odersky")))
def findById(id: Int): Option[Language] = languages.get(id)
def findAll = languages.values
def main(args: Array[String]) {
val language = Optional.findById(1)
if (language.isDefined) {
println(language.get.name)
}
}
val language = Optional.findById(3) None
Optional Type in Scala
val languages =Map("Java"->"Gosling","Scala"->"Odersky")
languages:scala.collection.immutale.Map[java.lang.String,java.lang.String]
languages get "Scala"
Option[java.lang.String] = Some(Odersky)
languages get "Groovy"
Option[java.lang.String] = None
Lambdas in streams
List<Book> books=Arrays.asList(book,book1,book2);
Optional<String> bookFiltered =
books.stream()
.filter(b -> b.getTitle().contains("Groovy"))
.map(b -> b.getTitle().toUpperCase())
.findFirst();
val books = Arrays.asList(book,book1,book2)
val bookFiltered : String? =
books.sequence()
.filter { b->b.title.contains("Groovy")}
.map { b->b.title.toUpperCase() }
.firstOrNull()
def bookfilter= books.
findAll { b->b.title.contains(" Groovy ") }
.sort { b->b.isbn }
.collect { b->b.title.toUpperCase() }
.find()
val bookList = List(book1,book2,book3);
val bookFilter = bookList
.filter(b=>b.title.contains("Groovy"))
.map(book => book.title)
Pattern matching
• Is a generalization of Java switch/case
def generalSize(x: Any) = x match {
case s: String => s.length
case m: Map[_, _] => m.size
case _ => -1
}
scala> generalSize("abc")
res: Int = 3
scala> generalSize(Map(1 -> 'a', 2 -> 'b'))
res: Int = 2
fun fib(n: Int): Int {
return when (n) {
1, 2 -> 1
else -> fib(n - 1) + fib(n - 2)
}
}
fun patternMatching(x:Any) {
when (x) {
is Int -> print(x)
is List<*> ->{print(x.size())}
is String -> print("String")
!is Number -> print("Not even a number")
else -> print("can't do anything")
}
}
Traits vs Java interfaces
Traits allow declare method definitions
A trait is an interface with an
implementation(behavior and/or state)
Traits support “multiple inheritance”
One class can inherit from many traits
Traits.Code in interfaces
trait Publication {
int number
def getNumberPublication(){
return (number)
}
}
trait Location {
String description
def getInfoPublication(){
return (description)
}
}
class MyBook implements Publication,Location{
Integer isbn
String title
def getInfoBook(){
return (isbn+ " "+title)
}
}
trait Publication {
def description() = println(“Description”)
}
class Book(var isbn:Int,var title:String) extends Publication{
def getInfoBook(){
return (isbn+ " "+title)
}
}
trait Publication{
var number:String
fun getNumberPublication(){
println(number)
}
}
class Book:Publication {
}
Java interoperability
object list extends App {
import java.util.ArrayList
var list : ArrayList[String] = new ArrayList[String]()
list.add("hello")
list.add("world")
println(list)
}
import collection.JavaConversions._
java.util.Arrays.asList(1,2,3).
foreach(i =>println(i))
java.util.Arrays.asList(1,2,3).
filter(_ % 2 ==0)
fun list(source: List<Int>):ArrayList<Int> {
val list = ArrayList<Int>()
for (item in source)
list.add(item)
for (i in 0..source.size() - 1)
list[i] = source[i]
return list
}
(ns clojure-http-server.core
(:require [clojure.string])
(:import (java.net ServerSocket SocketException)
(java.util Date)
(java.io PrintWriter BufferedReader
InputStreamReader BufferedOutputStream)))
Java interoperability
import scala.beans.BeanProperty
class Language(
@BeanProperty var name: String,
@BeanProperty var author: String) {
}
public static void main(String[] args) {
Language l1 = new Language(“Java",”Gosling”);
Language l2 = new Language(“Scala",”Odersky”);
ArrayList<Language> list = new ArrayList<>();
list.add(l1);
list.add(l2);
}
List Partitions
• We can use partition over a list for obtain 2 lists
scala> List(1, 2, 3, 4, 5) partition (_ % 2 == 0)
res: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5))
// partition the values 1 to 10 into a pair of lists of even and odd numbers
assertEquals(Pair(listOf(2, 4, 6, 8, 10), listOf(1, 3, 5, 7, 9)), (1..10)
.partition{ it % 2 == 0 })
Read file and print lines
import scala.io.Source
for (line <- Source.fromFile(“file.txt”).getLines())
println(line.length +" "+ line)
import java.nio.file.*;
import java.util.stream.Stream;
Path dict = Paths.get(“file.txt”);
Stream<String> linesStream = Files.lines(dict);
linesStream.forEach(System.out::println);
val dict = Paths.get(“file.txt")
val linesStream = Files.lines(dict)
val lines = linesStream.forEach{println(it)};
Read file and print lines
(defn read-file [file]
(with-open [rdr (clojure.java.io/reader file)]
(doseq [line (line-seq rdr)]
(println line))))
(read-file (file “file.txt"))
Files.lines(Paths.get(“file.txt")).forEach{println it};
Performance in recursion
(defn factorial ([x] (trampoline (factorial (dec x) x)))
([x a] (if (<= x 1) a #(factorial (dec x) (*' x a)))))
@TailRecursive
def fact(BigInteger n,acumulator = 1G) {
if (n <2){
acumulator
}else{
fact(n-1,n*acumulator)
}
}
@scala.annotation.tailrec
def factorialrec(fact:BigInt,number:BigInt=1):BigInt = {
if (fact<2) return number
else factorialrec(fact-1,fact*number)
}
Comparing features
Higher Order Functions
Mixin/traits
Pattern matching
Implicit casts
Nullables / Optionals
Modules
Promote inmutability
Lambdas
Palindrome
(use 'clojure.java.io)
(defn palindrome? [s]
(let [sl (.toLowerCase s)]
(= sl (apply str (reverse sl)))))
(defn find-palindromes[s]
(filter palindrome? (clojure.string/split s #" ")))
fun isPalindrome(s : String) : Boolean {
return s== s.reverse()
}
fun findPalindrome(s:List<String>): List<String>{
return s.filter {isPalindrome(it)}.map {it}
}
def isPalindrome(x:String) = x==x.reverse
def findPalindrome(s:Seq[String]) = s find isPalindrome
def isPalindrome(s) {
def s1 = s.toLowerCase()
s1 == s1.reverse()
}
def findAllPalindrome(list) {
list.findAll{isPalindrome(it)}
}
Conclusions
Full interoperability with Java
Reducing Java verbosity
These languages allow developer be more
productive comparing with java
Pragmatic Programmer advice: When you
learn a new language, you learn a new way
to think.
Resources
SCALA
• http://www.scala-lang.org
• http://www.scalakoans.org
• http://scala-ide.org
• https://www.coursera.org/course/progfun
KOTLIN
• http://kotlinlang.org
• http://kotlin.jetbrains.org
• http://kotlin-demo.jetbrains.com
• http://github.com/Jetbrains/kotlin
Resources
CLOJURE
• http://www.tryclj.com
• http://clojuredocs.org
• http://www.clojure-toolbox.com
• http://www.clojureatlas.com
CEYLON
• https://modules.ceylon-lang.org
Resources
• http://vschart.com/compare/kotlin/vs/clojure/vs/scala
Book
• Seven Languages in Seven Weeks
• A Pragmatic Guide to Learning Programming Languages
• https://pragprog.com/book/btlang/seven-languages-in-seven-weeks
• Ruby
• Io
• Prolog
• Scala
• Erlang
• Clojure
• Haskell
Thank you!
José Manuel Ortega Candel | @jmortegac

Mais conteúdo relacionado

Mais procurados

Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better JavaNils Breunese
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_ce
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardMario Fusco
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2José Paumard
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collectionsMyeongin Woo
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional ArchitectureJohn De Goes
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8Alonso Torres
 

Mais procurados (20)

Kotlin: a better Java
Kotlin: a better JavaKotlin: a better Java
Kotlin: a better Java
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
 
Orthogonal Functional Architecture
Orthogonal Functional ArchitectureOrthogonal Functional Architecture
Orthogonal Functional Architecture
 
[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8[Codemotion 2015] patrones de diseño con java8
[Codemotion 2015] patrones de diseño con java8
 

Destaque

The Delivery Hero - A Simpsons As A Service Storyboard
The Delivery Hero - A Simpsons As A Service StoryboardThe Delivery Hero - A Simpsons As A Service Storyboard
The Delivery Hero - A Simpsons As A Service StoryboardChristoph Engelbert
 
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...Lucidworks
 
Data Engineering with Solr and Spark
Data Engineering with Solr and SparkData Engineering with Solr and Spark
Data Engineering with Solr and SparkLucidworks
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Andrey Breslav
 
Project Panama - Beyond the (JVM) Wall
Project Panama - Beyond the (JVM) WallProject Panama - Beyond the (JVM) Wall
Project Panama - Beyond the (JVM) WallChristoph Engelbert
 

Destaque (6)

The Delivery Hero - A Simpsons As A Service Storyboard
The Delivery Hero - A Simpsons As A Service StoryboardThe Delivery Hero - A Simpsons As A Service Storyboard
The Delivery Hero - A Simpsons As A Service Storyboard
 
Gimme Caching - The JCache Way
Gimme Caching - The JCache WayGimme Caching - The JCache Way
Gimme Caching - The JCache Way
 
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...
Solr and Spark for Real-Time Big Data Analytics: Presented by Tim Potter, Luc...
 
Data Engineering with Solr and Spark
Data Engineering with Solr and SparkData Engineering with Solr and Spark
Data Engineering with Solr and Spark
 
Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?Who's More Functional: Kotlin, Groovy, Scala, or Java?
Who's More Functional: Kotlin, Groovy, Scala, or Java?
 
Project Panama - Beyond the (JVM) Wall
Project Panama - Beyond the (JVM) WallProject Panama - Beyond the (JVM) Wall
Project Panama - Beyond the (JVM) Wall
 

Semelhante a Comparing JVM languages

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of androidDJ Rausch
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 

Semelhante a Comparing JVM languages (20)

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...
 
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Scala
ScalaScala
Scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 

Mais de Jose Manuel Ortega Candel

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfJose Manuel Ortega Candel
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfJose Manuel Ortega Candel
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Jose Manuel Ortega Candel
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfJose Manuel Ortega Candel
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfJose Manuel Ortega Candel
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudJose Manuel Ortega Candel
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Jose Manuel Ortega Candel
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Jose Manuel Ortega Candel
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sJose Manuel Ortega Candel
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Jose Manuel Ortega Candel
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanJose Manuel Ortega Candel
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamJose Manuel Ortega Candel
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsJose Manuel Ortega Candel
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorJose Manuel Ortega Candel
 

Mais de Jose Manuel Ortega Candel (20)

Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdfAsegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
Asegurando tus APIs Explorando el OWASP Top 10 de Seguridad en APIs.pdf
 
PyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdfPyGoat Analizando la seguridad en aplicaciones Django.pdf
PyGoat Analizando la seguridad en aplicaciones Django.pdf
 
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
Ciberseguridad en Blockchain y Smart Contracts: Explorando los Desafíos y Sol...
 
Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops Evolution of security strategies in K8s environments- All day devops
Evolution of security strategies in K8s environments- All day devops
 
Evolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdfEvolution of security strategies in K8s environments.pdf
Evolution of security strategies in K8s environments.pdf
 
Implementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdfImplementing Observability for Kubernetes.pdf
Implementing Observability for Kubernetes.pdf
 
Computación distribuida usando Python
Computación distribuida usando PythonComputación distribuida usando Python
Computación distribuida usando Python
 
Seguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloudSeguridad en arquitecturas serverless y entornos cloud
Seguridad en arquitecturas serverless y entornos cloud
 
Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud Construyendo arquitecturas zero trust sobre entornos cloud
Construyendo arquitecturas zero trust sobre entornos cloud
 
Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python Tips and tricks for data science projects with Python
Tips and tricks for data science projects with Python
 
Sharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8sSharing secret keys in Docker containers and K8s
Sharing secret keys in Docker containers and K8s
 
Implementing cert-manager in K8s
Implementing cert-manager in K8sImplementing cert-manager in K8s
Implementing cert-manager in K8s
 
Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)Python para equipos de ciberseguridad(pycones)
Python para equipos de ciberseguridad(pycones)
 
Python para equipos de ciberseguridad
Python para equipos de ciberseguridad Python para equipos de ciberseguridad
Python para equipos de ciberseguridad
 
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodanShodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
Shodan Tips and tricks. Automatiza y maximiza las búsquedas shodan
 
ELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue TeamELK para analistas de seguridad y equipos Blue Team
ELK para analistas de seguridad y equipos Blue Team
 
Monitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source toolsMonitoring and managing Containers using Open Source tools
Monitoring and managing Containers using Open Source tools
 
Python Memory Management 101(Europython)
Python Memory Management 101(Europython)Python Memory Management 101(Europython)
Python Memory Management 101(Europython)
 
SecDevOps containers
SecDevOps containersSecDevOps containers
SecDevOps containers
 
Python memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collectorPython memory managment. Deeping in Garbage collector
Python memory managment. Deeping in Garbage collector
 

Último

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Último (20)

The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Comparing JVM languages

  • 1. Comparing JVM languages José Manuel Ortega Candel | @jmortegac 26-27 June 2015
  • 2. INDEX Functional programming and closures2 Language classification1 Java 8 new features3 Scala, Groovy, Kotlin, Clojure and Ceylon4 Advantages and drawbacks5 Comparing features6
  • 3. Language classification FUNCTIONAL NOT FUNCTIONAL STATIC DYNAMIC
  • 4. Functional programming •Data structure persistent and immutable •Closures •Higher order functions •Pass functions to functions as parameter •Create functions within functions •Return functions from other functions •Functions as first class values
  • 5. Closures •Reduce amount of “boiler plate” code •Eliminate the boilerplate code of anonymous inner classes •Allow the use of idiomatic functional programming code •Allow the creation of custom control structures •In Java 8 closures are just syntactic sugar for defining anonymous inner classes
  • 6. Java 8 new features  Lambda expressions  Closures  Streams  Enhaced collections  Processing data in parallel  Pattern Filter-Map-Reduce  Annotations types  Methods References (String s)-> System.out.println(s) System.out::println
  • 8. Filter-Map-Reduce Book book=new Book(123455,"Beginning Java 8"); Book book1=new Book(3232332,"Java 8 Advanced"); Book book2=new Book(43434343,"Groovy Advanced"); List<Book> books=Arrays.asList(book,book1,book2); Predicate<Book> condition=(it) -> it.getTitle().contains("Java"); String jsonFormat=books .stream() .filter(condition) .map(Book::toJSON) .collect(Collectors.joining(", ")); [{isbn:123455,title:'Beginning Java 8'}, {isbn:3232332,title:'Java 8 Advanced'}]
  • 9. Parallel Streams List myList = .. Stream stream = myList.stream(); Stream parallelStream = myList.parallelStream(); Stream parallel = stream.parallel(); •Streams are sequential by default •With Parallel you can optimize number of threads •More efficient with bigger collections
  • 10. Sequential vs Parallel books.parallelStream().filter((it) -> it.getTitle().contains("Java")). forEach((it)->System.out.println(it+" "+Thread.currentThread())); Book{isbn=3232332, title='Java 8 Advanced'} Thread[main,5,main] Book{isbn=123455, title='Beginning Java 8'} Thread[main,5,main] books.stream().filter((it) -> it.getTitle().contains("Java")). forEach((it)->System.out.println(it+" "+Thread.currentThread())); Book{isbn=3232332, title='Java 8 Advanced'} Thread[main,5,main] Book{isbn=123455, title='Beginning Java 8'} Thread[ForkJoinPool.commonPool- worker-2,5,main]
  • 11. Scala Combines the paradigms of functional programming and object-oriented Statically typed No types primitives like Java Everything is an Object, including functions Performance equivalent to Java
  • 12. Scala features Pattern matching Closures,lambdas,anonymous functions Traits and mixins for multiple inheritance Operator overloading Support Data Paralell like Java 8 Concurrency models(Akka,actors) Inmutable and mutable data structures
  • 13. Scala examples def factorial(n : Int): Int = n match{ case 0 => 1 case x if x >0 => factorial(n-1) *n } val languages = List("Scala", "Groovy", "Clojure", "Kotlin") val headList = languages.head // Scala val tailList = languages.tail; //List( "Groovy", "Clojure", "Kotlin") val empty = languages.isEmpty //false def orderList(xs: List[String]): List[String] = if (xs.isEmpty) Nil else insert(xs.head, isort(xs.tail) @BeanProperty Annotation which is read by the Scala compiler to generate getter and setter class Bean { @scala.reflect.BeanProperty var name: String } val someNumbers = List(-11, -10, -5, 0, 5, 10) someNumbers.filter((x) => x > 0) someNumbers.filter(_ > 0) List[Int] = List(5, 10) scala.collection.immutable
  • 14. Inmutability in Scala scala> var languages = Set("Scala", "Kotlin") languages : scala.collection.immutable.Set[java.lang.String] = Set(Scala, Kotlin) scala> languages += "Clojure" scala> languages res: scala.collection.immutable.Set[java.lang.String] = Set(Scala, Kotlin, Clojure) scala> languages -= " Kotlin " scala> languages res: scala.collection.immutable.Set[java.lang.String] = Set(Scala, Clojure) • You can add elements in a inmutable collection
  • 15. Java 8 vs Scala
  • 16. Java 8 vs Scala streams bookList.parallelStream().filter(b -> b.title.equals(”Clojure”)) .collect(Collectors.toList()) bookList.par.filter(_.title == “Clojure”) bookList.par.filter( b =>b.title == “Clojure”) val bookFilter = bookList.par.filter(_.title.contains("Groovy")) .foreach{i=> println(Thread.currentThread) } Thread[ForkJoinPool-1-worker-3,5,main] Thread[ForkJoinPool-1-worker-5,5,main]
  • 17. Kotlin Object-oriented with functional elements Developed by JetBrains Statically typed like Scala Smarts casts Elvis operator(?) for checking null like Groovy Type inference 100 % interoperability with Java
  • 18. Kotlin syntax & rules Inmutable/Mutable variables No new keyword for create objects No primitive types No static members Primary constructors No fields, just properties By default, all classes are final
  • 19. Kotlin Smart casts Maps val languages = mapOf("Java" to "Gosling", "Scala" to "Odersky","Groovy" to "Strachan") for((language,author) in languages){ println("$author made $language") } fun eval(e: Expr): Double = when (e) { is Num-> e.value.toDouble() is Sum -> eval(e.left) + eval(e.right) else -> throw IllegalArgumentException("Unknown expression") } val mapLanguages = hashMapOf<String, String>() mapLanguages.put("Java", "Gosling") mapLanguages.put("Scala", "Odersky") for ((key, value) in mapLanguages) { println("key = $key, value = $value") } fun patternMatching(x:Any) { when (x) { is Int -> print(x) is List<*> ->{print(x.count())} is String -> print(x.length()) !is Number -> print("Not even a number") else -> print("can't do anything") } }
  • 20. Kotlin Operator overloading Default & name arguments println(product(2)) println(product(2,3)) println(format(text="kotlin")) println(format(text="kotlin", upperCase= true)) 2 6 kotlin KOTLIN fun product(a:Int,b:Int=1):Int{ return a.times(b); } fun format(text:String,upperCase:Boolean= false):String { return if (upperCase) text.toUpperCase() else text }
  • 21. Kotlin Iterators fun iterateOverCollection(collection: Collection<Int>) { for (element in collection) {} } fun iterateOverString() { for (c in "abcd") {} "abcd".iterator() } fun iteratingOverMap(map: Map<Int, String>) { for ((key, value) in map) {} }
  • 22. Kotlin Data classes  Data annotation changes behavior of hashCode, equals, toString functions public class Book (var isbn:Int, var title:String) fun main(args: Array<String>) { //Books val book = Book(123456, "Beginning Kotlin") val book2 = Book(123456, "Beginning Kotlin") println(book); println(book.hashCode()); println(book2.hashCode()); println(book.equals(book2)); if (book == book2) println("Same Book"); if (book != book2) println("Diferent Book"); } books.Book@2a84aee7 713338599 168423058 false Diferent Book data public class Book (var isbn:Int, var title:String) fun main(args: Array<String>) { //Books val book = Book(123456, "Beginning Kotlin") val book2 = Book(123456, "Beginning Kotlin") println(book); println(book.hashCode()); println(book2.hashCode()); println(book.equals(book2)); if (book == book2) println("Same Book"); if (book != book2) println("Diferent Book"); Book(isbn=123456, title=Beginning Kotlin) 1848623012 1848623012 true Same Book
  • 23. Kotlin Classes constructor • It is not necessary define a constructor like in Java • You can use the class definition to pass the properties and default values data public class Book (var isbn:Int, var title:String="My Default Book") fun main(args: Array<String>) { val book = Book(123456) println(book.title); }
  • 24. Kotlin Higher order functions • Lambda expressions • it implicit parameter val filter = books filter({ b: Book -> b.title.contains(“Kotlin") }) val book = Book(123455, "Beginning Java 8") val book1 = Book(3232332, "Java 8 Advanced") val book2 = Book(43434343, “Kotlin Advanced") val books = Arrays.asList(book, book1,book2) Filter[Book(isbn=43434343, title=Kotlin Advanced)] val filter = books filter({ it.contains(“Kotlin") })
  • 25. Kotlin collections val listInmutable =listOf("Java","Kotlin","Groovy","Scala") val listMutable=ArrayList<String>() listMutable.add("Java") listMutable.add("Kotlin")
  • 26. Kotlin vs Java list iterate for ((index,element) in list.withIndex()) { println(“$index$element”); } int index=0 for (String element:list) { System.out.println(index+””+element); index++ }
  • 27. Kotlin smart cast vs Java if (expr is Number) { println(expr.getValue()); //expr is automatically cast to Number } if (expr instanceof Number) { System.out.println((Number)expr).getValue()); }
  • 28. Kotlin vs Java types inference val longJavaClassName = LongJavaClassName() LongJavaClassName longJavaClassName =new LongJavaClassName()
  • 29. Groovy  Java supercharged(syntactic sugar)  Object oriented and dynamic language  Optional typing like Scala and Kotlin  All type checking is at run time  It reduces Java boilerplate code including no semi colons, no getters/setters, type inference, null safety, elvis operators
  • 30. Groovy  Closures with lambda or it implicit parameter def upper = { s-> s.toUpperCase()} def upper = {it.toUpperCase()}  Collections def languages = ["Java":”James Gosling”, "Scala":”Martin Odersky”, "Clojure":”Rich Hickey”, "Ceylon":”Gavin King”, "Groovy":”James Strachan”] languages.each { entry -> println} languages.each { k,v -> println}  Methods as closures with .& operator def object object = 2 object = true object = [1,2,3]  Optional typing
  • 31. Groovy  @Memoized annotation  @Inmutable annotation @Memoized def BigInteger fibRecursiveMemoized(n) { if (n<2) return 1 else return fibRecursiveMemoized(n-1) + fibRecursiveMemoized(n-2) } TimeIt.code{println(fibonnaci.fibRecursive(40))} TimeIt.code{println(fibonnaci.fibRecursiveMemoized(40))} 165580141 Time taken 42.083165464 seconds 165580141 Time taken 0.061408655 seconds //with memoize import groovy.transform.Immutable @Immutable class Language { String title; Long isbn; } def l1 = new Language (title:'Beginning Groovy',isbn:100) def l2 = new Language (title:'Groovy advanced',isbn:200) l1.title = 'Groovy for dummies' // Should fail with groovy.lang.ReadOnlyPropertyException
  • 32. Groovy  Time execution class TimeIt { def static code(codeBlock){ def start = System.nanoTime() try{ codeBlock() }finally{ def end = System.nanoTime() println "Time taken ${(end-start)/1e9} seconds" } } }
  • 33. Groovy  Parsing and creating XML
  • 34. Groovy Advantages Disadvantages Java Collections Non-lazy evaluation Closures (like Lambda expressions in Java 8) It's performance isn't great (but it's improving) Filter – Map – Reduce in streams Easy interoperability with Java Static and dynamic typing @TypeChecked @CompileStatic Metaprogramming
  • 35. Java Groovy def languages = ["Java", "Scala", "Clojure", "Kotlin", "Ceylon","Groovy"] def filter = languages.stream() .findAll { it.size()>5 } .collect { it.toUpperCase()} .first() List<String> languages = Arrays.asList("Java", "Scala", "Clojure", "Kotlin","Ceylon","Groovy"); Optional<String> bookFiltered = languages.stream() .filter(s -> s.length()>5 ) .map(s -> s.toUpperCase()) .findFirst();
  • 36. Clojure Pure functional language JVM language based in Lisp Not Object Oriented Dynamically typed All data structure including list ,vectors, maps, sequences, collections, are inmutable and fully persistent The main data structure is the list The key is the use of High Order Functions
  • 37. Clojure Alternate implementations in functions (defn square-or-multiply "squares a single argument, multiplies two arguments" ([] 0) # without arguments ([x] (* x x)) # one argument ([x y] (* x y))) # two arguments List operations (first '(:scala :groovy :clojure))return scala (rest '(:scala :groovy :clojure))return all elements excepts the first (cons :kotlin '(:scala :groovy :clojure))add kotlin to head in the list
  • 38. Clojure Sequences (defn count-down [n] (if (<= n 0) '(0) (cons n (lazy-seq (count-down (dec n)))))) Filter – Map - Reduce (filter integer? [1 2.71 3.14 5 42]) => (1 5 42) (map (fn [n] (* n n)) [1 2 3 4 5]) => (1 4 9 16 25) (reduce + [1 2 3 4]) => 10 user=> (count-down 8) (8 7 6 5 4 3 2 1 0)
  • 39. Clojure Records (defrecord Book [isbn title]) (def bookList [(Book. 432423 "Clojure")(Book. 534243 "Kotlin") (Book. 432424 "Groovy")]) (println "count bookList "(count bookList)) (dorun (for [item bookList] (println (:title item)(:isbn item)))) (println (filter #(= "Clojure" (get % :title)) bookList)) count bookList 3 Clojure 432423 Kotlin 534243 Groovy 432424 (#user.Book{:isbn 432423, :title Clojure}) (defrecord Object [prop1 propn])
  • 40. Clojure Recursive functions with trampoline and memoize (defn factorial ([x] (trampoline (factorial (dec x) x))) ([x a] (if (<= x 1) a #(factorial (dec x) (*' x a))))) (def fibonaci (memoize (fn [n] (if (< n 2) n (+ (fibonaci (dec n)) (fibonaci (dec (dec n)))))))) (time(println (factorial 20))) (time(println (fibonaci 30))) "Elapsed time: 0.692549 msecs" 832040 "Elapsed time: 1.263175 msecs" "Elapsed time: 24.574218 msecs" 832040 "Elapsed time: 118.678434 msecs" 2432902008176640000
  • 41. Clojure Advantages Disadvantages Very simple Not Object oriented The language has little elements compared with other languages Difficult to decipher stacktraces and errors Excellent concurrency support Requires a new way to solve problems Easy interoperability with java There are no variables Powerful language features (macros,protocols) Thre is no inheritance concept Clojure programs run very quickly No mecanism for avoid NullPointerException JVM is highly optimized
  • 42. Clojure vs Java Code reducing (defn blank [str] (every#? (Character/isWhitespace %) str)) public class StringUtils { public static boolean isBlank(String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(str.charAt(i)))) { return true; }} return false; }}
  • 43. Ceylon Is very similar to Java, reducing verbosity Object oriented with functional features Strong static typing with type inference Explicit module system  Comparing with Java  Eliminates static, public, protected, private  Add new modifiers like variable, shared, local  Shared is used for make visibility outside in other modules(like public in Java)  Arrays are replaced by sequences
  • 44. Ceylon Sequence languages = Sequence("Java", "Groovy","Clojure","Kotlin"); //Check if the sequence is empty if(nonempty languages){ String? firstElementValue = languages.value(1); String? firstElement = languages.first; } Sequence more = join(languages,Sequence("Ceylon","Scala")); Sequences Generics & Union types Iterable<String|Boolean> list = {“string”,true,false} ArrayList<Integer|Float> list = ArrayList<Integer|Float> (1, 2, 1.0, 2.0)
  • 45. Comparing featues •Reducing verbosity •Variables definition •Null-safety •Optional types •Lambdas •Pattern matching •Traits •Java interoperability
  • 46. Reducing Java verbosity Reducing Boilerplate Code class MyClass{ private int index; private String name; public MyClass(int index, String name){ this.index = index; this.name = name; } } case class MyClass(index: Int, name: String) public class MyClass(var index:Integer,var name:String){ } class MyClass { int index String name } class MyClass(index,name) { shared Integer index; shared String name; } (defstruct MyClass :index :name)
  • 47. Variables definition • In Kotlin and Scala you can define 2 types • var myMutableVariable • val myInmutableVariable • In Ceylon we have variable modifier for mutable variable Integer count=0; count++; //OK Integer count=0; count++;//ERROR val name: Type = initializer // final “variable” var name: Type = initializer // mutable variable
  • 48. Null-safety •Operator ? used in Kotlin,Groovy,Ceylon •Avoid NullPointerException var b : String? = "b" b = null // valid null assignment val l = b?.length() Elvis Operator(?:) and Safe navigation (?.) def displayName = user.name ? user.name : "Anonymous“ def streetName = user?.address?.street String? argument = process.arguments.first; if (exists argument) { //checking null values }
  • 49. Optional Types Optional<Object> optional = findObject(id); //check if Optional object has value if (optional.isPresent()) { System.out.println(optional.get()); } Type safe Option[T] in Scala New class java.util.Optional
  • 50. Optional Type in Scala private val languages = Map(1 -> Language(1, "Java", Some("Gosling")), 2 -> Language(2, "Scala", Some("Odersky"))) def findById(id: Int): Option[Language] = languages.get(id) def findAll = languages.values def main(args: Array[String]) { val language = Optional.findById(1) if (language.isDefined) { println(language.get.name) } } val language = Optional.findById(3) None
  • 51. Optional Type in Scala val languages =Map("Java"->"Gosling","Scala"->"Odersky") languages:scala.collection.immutale.Map[java.lang.String,java.lang.String] languages get "Scala" Option[java.lang.String] = Some(Odersky) languages get "Groovy" Option[java.lang.String] = None
  • 52. Lambdas in streams List<Book> books=Arrays.asList(book,book1,book2); Optional<String> bookFiltered = books.stream() .filter(b -> b.getTitle().contains("Groovy")) .map(b -> b.getTitle().toUpperCase()) .findFirst(); val books = Arrays.asList(book,book1,book2) val bookFiltered : String? = books.sequence() .filter { b->b.title.contains("Groovy")} .map { b->b.title.toUpperCase() } .firstOrNull() def bookfilter= books. findAll { b->b.title.contains(" Groovy ") } .sort { b->b.isbn } .collect { b->b.title.toUpperCase() } .find() val bookList = List(book1,book2,book3); val bookFilter = bookList .filter(b=>b.title.contains("Groovy")) .map(book => book.title)
  • 53. Pattern matching • Is a generalization of Java switch/case def generalSize(x: Any) = x match { case s: String => s.length case m: Map[_, _] => m.size case _ => -1 } scala> generalSize("abc") res: Int = 3 scala> generalSize(Map(1 -> 'a', 2 -> 'b')) res: Int = 2 fun fib(n: Int): Int { return when (n) { 1, 2 -> 1 else -> fib(n - 1) + fib(n - 2) } } fun patternMatching(x:Any) { when (x) { is Int -> print(x) is List<*> ->{print(x.size())} is String -> print("String") !is Number -> print("Not even a number") else -> print("can't do anything") } }
  • 54. Traits vs Java interfaces Traits allow declare method definitions A trait is an interface with an implementation(behavior and/or state) Traits support “multiple inheritance” One class can inherit from many traits
  • 55. Traits.Code in interfaces trait Publication { int number def getNumberPublication(){ return (number) } } trait Location { String description def getInfoPublication(){ return (description) } } class MyBook implements Publication,Location{ Integer isbn String title def getInfoBook(){ return (isbn+ " "+title) } } trait Publication { def description() = println(“Description”) } class Book(var isbn:Int,var title:String) extends Publication{ def getInfoBook(){ return (isbn+ " "+title) } } trait Publication{ var number:String fun getNumberPublication(){ println(number) } } class Book:Publication { }
  • 56. Java interoperability object list extends App { import java.util.ArrayList var list : ArrayList[String] = new ArrayList[String]() list.add("hello") list.add("world") println(list) } import collection.JavaConversions._ java.util.Arrays.asList(1,2,3). foreach(i =>println(i)) java.util.Arrays.asList(1,2,3). filter(_ % 2 ==0) fun list(source: List<Int>):ArrayList<Int> { val list = ArrayList<Int>() for (item in source) list.add(item) for (i in 0..source.size() - 1) list[i] = source[i] return list } (ns clojure-http-server.core (:require [clojure.string]) (:import (java.net ServerSocket SocketException) (java.util Date) (java.io PrintWriter BufferedReader InputStreamReader BufferedOutputStream)))
  • 57. Java interoperability import scala.beans.BeanProperty class Language( @BeanProperty var name: String, @BeanProperty var author: String) { } public static void main(String[] args) { Language l1 = new Language(“Java",”Gosling”); Language l2 = new Language(“Scala",”Odersky”); ArrayList<Language> list = new ArrayList<>(); list.add(l1); list.add(l2); }
  • 58. List Partitions • We can use partition over a list for obtain 2 lists scala> List(1, 2, 3, 4, 5) partition (_ % 2 == 0) res: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5)) // partition the values 1 to 10 into a pair of lists of even and odd numbers assertEquals(Pair(listOf(2, 4, 6, 8, 10), listOf(1, 3, 5, 7, 9)), (1..10) .partition{ it % 2 == 0 })
  • 59. Read file and print lines import scala.io.Source for (line <- Source.fromFile(“file.txt”).getLines()) println(line.length +" "+ line) import java.nio.file.*; import java.util.stream.Stream; Path dict = Paths.get(“file.txt”); Stream<String> linesStream = Files.lines(dict); linesStream.forEach(System.out::println); val dict = Paths.get(“file.txt") val linesStream = Files.lines(dict) val lines = linesStream.forEach{println(it)};
  • 60. Read file and print lines (defn read-file [file] (with-open [rdr (clojure.java.io/reader file)] (doseq [line (line-seq rdr)] (println line)))) (read-file (file “file.txt")) Files.lines(Paths.get(“file.txt")).forEach{println it};
  • 61. Performance in recursion (defn factorial ([x] (trampoline (factorial (dec x) x))) ([x a] (if (<= x 1) a #(factorial (dec x) (*' x a))))) @TailRecursive def fact(BigInteger n,acumulator = 1G) { if (n <2){ acumulator }else{ fact(n-1,n*acumulator) } } @scala.annotation.tailrec def factorialrec(fact:BigInt,number:BigInt=1):BigInt = { if (fact<2) return number else factorialrec(fact-1,fact*number) }
  • 62. Comparing features Higher Order Functions Mixin/traits Pattern matching Implicit casts Nullables / Optionals Modules Promote inmutability Lambdas
  • 63. Palindrome (use 'clojure.java.io) (defn palindrome? [s] (let [sl (.toLowerCase s)] (= sl (apply str (reverse sl))))) (defn find-palindromes[s] (filter palindrome? (clojure.string/split s #" "))) fun isPalindrome(s : String) : Boolean { return s== s.reverse() } fun findPalindrome(s:List<String>): List<String>{ return s.filter {isPalindrome(it)}.map {it} } def isPalindrome(x:String) = x==x.reverse def findPalindrome(s:Seq[String]) = s find isPalindrome def isPalindrome(s) { def s1 = s.toLowerCase() s1 == s1.reverse() } def findAllPalindrome(list) { list.findAll{isPalindrome(it)} }
  • 64. Conclusions Full interoperability with Java Reducing Java verbosity These languages allow developer be more productive comparing with java Pragmatic Programmer advice: When you learn a new language, you learn a new way to think.
  • 65. Resources SCALA • http://www.scala-lang.org • http://www.scalakoans.org • http://scala-ide.org • https://www.coursera.org/course/progfun KOTLIN • http://kotlinlang.org • http://kotlin.jetbrains.org • http://kotlin-demo.jetbrains.com • http://github.com/Jetbrains/kotlin
  • 66. Resources CLOJURE • http://www.tryclj.com • http://clojuredocs.org • http://www.clojure-toolbox.com • http://www.clojureatlas.com CEYLON • https://modules.ceylon-lang.org
  • 68. Book • Seven Languages in Seven Weeks • A Pragmatic Guide to Learning Programming Languages • https://pragprog.com/book/btlang/seven-languages-in-seven-weeks • Ruby • Io • Prolog • Scala • Erlang • Clojure • Haskell
  • 69. Thank you! José Manuel Ortega Candel | @jmortegac