functions •Pass functions to functions as parameter •Create functions within functions •Return functions from other functions •Functions as first class values
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
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
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
: 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
"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") } }
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
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); }
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
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
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
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
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
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
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
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") } }
@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); }