Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Scala workshop
                   Created by
    Fredrik Vraalsen (fredrik@vraalsen.no)
                       and
  Alf Kristian Støyle (alf.kristian@gmail.com)

                   Adapted
Bert Van Vreckem (bert.vanvreckem@hogent.be)
If I were to pick a language to use
today other than Java, it would be
                Scala.

          James Gosling
Scala, it must be stated, is the current heir
apparent to the Java throne. No other language
   on the JVM seems as capable of being a
   "replacement for Java" as Scala, and the
momentum behind Scala is now unquestionable.

      Charlies Olivier Nutter - JRuby lead
Though my tip though for the long term
  replacement of javac is Scala. I'm very
   impressed with it! I can honestly say if
someone had shown me the Programming
 in Scala book by by Martin Odersky, Lex
   Spoon & Bill Venners back in 2003 I'd
    probably have never created Groovy.

             James Strachen

Recommended for you

All about scala
All about scalaAll about scala
All about scala

The document is a slide presentation on Scala that provides an introduction to the language in 90 minutes or less. It covers Scala basics like being object oriented and functional, static typing, compilation to JVM bytecode, and interoperability with Java. It also discusses Scala tools, its use in open source projects and industry, recommended books, and jobs involving Scala. Code examples are provided to demonstrate Hello World programs, variables, methods, conditionals, sequences, and closures in Scala.

scala
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World

Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8. Video Presentation: http://youtu.be/8vxTowBXJSg

bti360java 8scala
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf

Martin Odersky discusses the past, present, and future of Scala over the past 5 years and next 5 years. Key points include: - Scala has grown significantly in usage and community over the past 6 years since its first release. - Scala 2.8 will include improvements like new collections, package objects, named/default parameters, and better tool support. - Over the next 5 years, Scala will focus on improving concurrency and parallelism through better abstractions, analyses, and static typing support.

public class Person {
    private int age;
    private String name;

      public Person(int age, String name) {
        this.age = age;
        this.name = name;
      }

      public int getAge() {
        return this.age;
      }

      public void setAge(int age) {
        this.age = age;
      }

      public String getName() {
        return this.name;
      }

      public void setName(String name) {
        this.name = name;
      }
  }



class Person(var age: Int,
             var name: String)
List<Person> persons = ...
List<Person> adults = new LinkedList<Person>();
List<Person> kids = new LinkedList<Person>();
for (Person person : persons) {
  if (person.getAge() < 18) {
    kids.add(person);
  } else {
    adults.add(person);
  }
}




     val (kids, adults) =
       persons.partition(_.age < 18)
String s = "!em esreveR";
System.out.println(s.reverse());




     val s = "!em esreveR"
     println(s.reverse)

     => Reverse me!
BufferedReader reader = null;
try {
  reader = new BufferedReader(new FileReader("f.txt"));
  System.out.println(reader.readLine());
} finally {
  if (reader != null) {
    try {
      reader.close();
    } catch (IOException e) {
      // Exception on close, ignore
    }
  }
}



using(new BufferedReader(new FileReader("f.txt"))) {
    reader => println(reader.readLine())
}

Recommended for you

Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals

This document provides an overview of Scala fundamentals including: - Scala is a programming language for the JVM that supports both object-oriented and functional paradigms. - It defines variables, values, lazy values, functions, types, classes, objects, traits, and higher-order functions. - Classes can extend other classes and traits, allowing for multiple inheritance. Objects are used as singletons. - Functional concepts like immutability, anonymous functions, and higher-order functions are supported.

scalatutorialfunctional programming
Scala introduction
Scala introductionScala introduction
Scala introduction

Scala is an object-oriented and functional programming language that runs on the Java Virtual Machine. It was created in 2001 by Martin Odersky and aims to integrate features of object-oriented and functional languages. Scala code is compiled to JVM bytecode and supports interoperability with Java libraries and frameworks. Some key features of Scala include support for immutable data structures, pattern matching, traits for mixing composition, and functional programming constructs like functions as first-class values. Scala has gained popularity in industry at companies like LinkedIn, Twitter, and The Guardian.

scala
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008

This document provides an introduction to the Scala programming language. It begins with an overview of Scala's motivation and history. It then covers the basics of Scala including simple data structures, loops, objects, types and generics. More advanced topics such as traits, mixins, implicit conversions and sealed classes are also discussed. The document concludes with references for further reading.

scala
I will never forget these words: "With great power
  comes great responsibility." This is my gift, my
         curse. Who am I? I'm Spider-man.
val myList = List(1, 2, 3)
val res = (10 /: myList)(_+_)


=> ??
Scala
●   Object oriented and functional
●   Statically typed
●   Java compatible
    ●   Complies to Java bytecode (and CLR)
    ●   Existing libraries/frameworks
●   Better Java
Todays schedule
●   Basic syntax
●   REPL, IDEs and setup
●   First class functions
●   Pattern matching
●   OO and traits
●   Functional programming
●   Higher order functions

Recommended for you

Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala

Android is a fast-growing mobile operating system with millions of users worldwide. Scala is a modern programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Why not combine both of them?

javascalaandroid
Scala on Android
Scala on AndroidScala on Android
Scala on Android

This document provides an overview of the Scala programming language and discusses its usage on Android. Scala is a multi-paradigm language that integrates object-oriented and functional programming. It runs on the Java Virtual Machine and is used by companies like LinkedIn, Twitter, and The Guardian. Scala's features include being object-oriented, functional, statically typed, and expressive while allowing concise code. It supports classes, traits, pattern matching, and lazy evaluation among other things.

androidscala
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...

Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organized by Knoldus Software LLP in New Delhi

scala traitsknoldus slidesharescala
Scala basics
;
Type definitions
Scala               Java

s: String           String s
i: Int              int i / Integer i
Variables
Scala:                   Java:

val s = "Hello World"    public final String s =
                           "Hello World";

var i = 1
                         public int i = 1;

private var j = 3
                         private int j = 3;

Recommended for you

Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes

Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases. A talk given at the Underscore meetup on 19 August, 2014.

underscorescalatype classes
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review

Slides from my talk at the Junction (Jan 24, 2013) Single-core performance has hit a ceiling, and building web-scale multi-core applications using imperative programming models is nightmarishly difficult. Parallel programming creates a new set of challenges, best practices and design patterns. Scala is designed to enable building scalable systems, elegantly blending functional and object oriented paradigms into an expressive and concise language, while retaining interoperability with Java. Scala is the fastest growing JVM programming language, being rapidly adopted by leading companies such as Twitter, LinkedIn and FourSquare. This presentation provides a comprehensive overview of the language, which managed to increase type safety while feeling more dynamic, being more concise and improving readability at the same time. We will see how Scala simplifies real life problems by empowering the developer with powerful functional programming primitives, without giving up on the object oriented paradigm. The overview includes tools for multi-core programming in Scala, the type system, collection framework and domain-specific languages. We’ll explore the power of compile-time meta-programming, which is made possible by the newly released Scala 2.10, and get a glimpse into what to expect from 2.11 in 2014. We will also see how Scala helps overcome the inherent limitations of Java, such as type erasure, array covariance and boxing overhead. Multiple examples emphasize how Scala pushes the JVM harder than any other mainstream language through the infinite number of boilerplate busters, increased type safety and productivity boosters from a Java developer’s perspective.

scalamulti-core programmingjvm
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf

This document introduces developing a Scala DSL for Apache Camel. It discusses using Scala techniques like implicit conversion, passing functions as parameters, by-name parameters and currying to build a DSL. It provides examples of building simple routes in the Scala DSL using these techniques and compares them to the Java DSL. It also covers some caveats like interactions between Java and Scala generics and operator precedence. The goal is to introduce basic Scala concepts and syntax that can be used to build a Scala DSL, using Apache Camel as an example.

Methods (3)
Scala:                        Java:

override def toString = ...   @Override
                              public String toString()
                                {...}
Classes and constructors
Scala:                   Java:

class Person(val name:   public class Person {
  String)                   private final String
                              name;
                            public Person(String
                              name) {
                               this.name = name;
                            }
                            public String getName() {
                               return name;
                            }
                         }
Traits (= Interface + Mixin)
Scala:                        Java:

trait Shape {                 interface Shape {
   def area: Double              public double area();
}                             }

class Circle extends Object   public class Circle extends
  with Shape                    Object implements Shape
No “static” in Scala
Scala:                           Java:

object PersonUtil {              public class PersonUtil {
  val ageLimit = 18                 public static final int
                                      AGE_LIMIT = 18;

    def countPersons(                public static int
      persons: List[Person]) =         countPersons(
      ...                                List<Person> persons)
}                                    {
                                         ...
                                     }
                                 }

Recommended for you

An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers

The document provides an introduction to Scala for Java developers. It outlines key features of Scala including cleaning up Java syntax, going beyond Java with features like case classes, traits, and pattern matching, and its functional focus including support for higher-order functions, the Option type, and for comprehensions. The document also briefly discusses the Scala IDE for Eclipse.

spascala
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala

The great attractiveness of purely functional languages is their ability to depart from sequential order of computation. Theoretically, it enables two important features of the compiler: 1) The ability to reorder computation flow, making the program implicitly parallelisable. Modern imperative language compilers, even using careful synchronization of concurrent code, still generate huge chunks of sequential instructions that need to be executed on a single processor core; a purely functional language compilers can dispatch very small chunks to many (hundreds and thousands) of cores, carefully eliminating as many execution path dependencies as possible. 2) As the compiler formalizes different types of side effects, it can detect a whole new class of program errors at compile time, including resource acquisition and releasing problems, concurrent access to shared resources, many types of deadlocks etc. It is not yet a full-fledged program verification, but it is a big step in that direction. Scala is a semi-imperative language with strong support for functional programming and rich type system. One can isolate the purely functional core of the language which can be put on the firm mathematical foundation of dependent type theories. We argue that it is possible to treat Scala code as it's written by now as an implicit do-notation which can be then reduced to a purely functional core by means of recently introduced Scala macros. The formalism of arrows and applicative contexts can bring Scala to a full glory of an implicitly parallelisable programming language, while still keeping its syntax mostly unchanged.

arrowscircuitriesmonads
Scala+RDD
Scala+RDDScala+RDD
Scala+RDD

A slide used to introduce scala and rdd in china mobile

sparkscalardd
While-loops
Scala:                 Java:

while (true) {         while (true) {
    ...                    ...
}                      }
Exceptions
Scala:                    Java:

throw new                 throw new
  Exception(“...”)          Exception(“...”)

try {                     try {
} catch {                 } catch (IOException e) {
   case e: IOException       ...
     => ...               } finally {
} finally {               }
}
Varargs
def foo(values: String*){ }     public void foo(String... values){ }


foo("bar", "baz")               foo("bar", "baz");


val arr = Array("bar", "baz")   String[] arr =
                                  new String[]{"bar", "baz"}
foo(arr: _*)                    foo(arr);
(Almost) everything is an expression
val res = if (foo) x else y


val res = for (i <- 1 to 10) yield i
   // List(1, ..., 10)


val res = try { x } catch { ...; y }
 finally { } // x or y

Recommended for you

ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings

Here are the answers to your questions: 1. The main differences between a Trait and Abstract Class in Scala are: - Traits can be mixed in to classes using with, while Abstract Classes can only be extended. - Traits allow for multiple inheritance as they can be mixed in, while Abstract Classes only allow single inheritance. - Abstract Classes can have fields and constructor parameters while Traits cannot. - Abstract Classes can extend other classes, while Traits can only extend other Traits. 2. abstract class Animal { def isMammal: Boolean def isFriendly: Boolean = true def summarize: Unit = { println("Characteristics of animal:") }

Scala+spark 2nd
Scala+spark 2ndScala+spark 2nd
Scala+spark 2nd

2nd version of scala & spark presentation.

fpscalaspark
Scala meetup - Intro to spark
Scala meetup - Intro to sparkScala meetup - Intro to spark
Scala meetup - Intro to spark

This document provides an introduction to Apache Spark, including its core components, architecture, and programming model. Some key points: - Spark uses Resilient Distributed Datasets (RDDs) as its fundamental data structure, which are immutable distributed collections that allow in-memory computing across a cluster. - RDDs support transformations like map, filter, reduce, and actions like collect that return results. Transformations are lazy while actions trigger computation. - Spark's execution model involves a driver program that coordinates tasks on worker nodes using an optimized scheduler. - Spark SQL, MLlib, GraphX, and Spark Streaming extend the core Spark API for structured data, machine learning, graph processing, and stream processing

big datascalakafka
Generics
Scala:             Java:

List[String]       List<String>
Tuples
Scala:                   Java:

val tuple: Tuple2[Int,   Pair<Integer, String> tuple
  String] =                = new Pair<Integer,
                           String>(1, “apple”)
  (1, “apple”)


val quadruple =
                         ... yeah right... ;-)
  (2, “orange”, 0.5d,
    false)
Packages
Scala:                  Java:

package mypackage       package mypackage;
...                     ...
Imports
Scala:                        Java:

import java.util.{List,       import java.util.List
  ArrayList}
                              import java.util.ArrayList


import java.io._
                              import java.io.*
import scala.util.Sorting._   ???

import java.sql.{Date =>      ???
  SDate}

Recommended for you

One vagrantfile to rule them all
One vagrantfile to rule them allOne vagrantfile to rule them all
One vagrantfile to rule them all

Slides for my lightning talk at Config Management Camp 2016. See the video here: https://youtu.be/qJ0VNO6z68M Writing Vagrantfiles is tedious, especially when you’re setting up a multi-VM environment. Typically, people will copy/paste code blocks that define hosts, but that becomes unwieldy. However, a Vagrantfile is “just” Ruby, so can’t we simplify things a bit using the power of the language? Turns out, we can! In this presentation I propose a reusable Vagrantfile that reads the configuration of the environment from a simple YAML file. See my blog post about this at https://bertvv.github.io/notes-to-self/2015/10/05/one-vagrantfile-to-rule-them-all/

vagrant
Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015

- The document discusses a presentation given by Jongwook Woo on introducing Spark and its uses for big data analysis. It includes information on Woo's background and experience with big data, an overview of Spark and its components like RDDs and task scheduling, and examples of using Spark for different types of data analysis and use cases.

sparkbig datascala
NYC_2016_slides
NYC_2016_slidesNYC_2016_slides
NYC_2016_slides

This document provides an overview of a machine learning workshop including tutorials on decision tree classification for flight delays, clustering news articles with k-means clustering, and collaborative filtering for movie recommendations using Spark. The tutorials demonstrate loading and preparing data, training models, evaluating performance, and making predictions or recommendations. They use Spark MLlib and are run in Apache Zeppelin notebooks.

REPL, IDE and setup
REPL: Read-Eval-Print Loop
●   Command line shell for on-the-fly execution of
    Scala statements
●
    $ cd ${SCALA_HOME}/bin
    $ scala
    ●   Windows, e.g. C:Program FilesScala 2.8.0
    ●   Linux, e.g. /opt/scala or /usr/local/scala
IDE
●   They are all !#$&§? compared to what you are
    used to with Java support
    ●   Netbeans (very good) but bad in other areas...
    ●   IntelliJ IDEA (pretty good) but slow compilation,
        bonus community edition is free (with Scala)
    ●   Eclipse (not all that good) but very fast when
        working
Netbeans 6.9.x installation
●   Download plugins
    http://sf.net/projects/erlybird/files/nb-scala/6.9v1.1.0/
●   In NetBeans "Tools" | "Plugins",
     ●   click on "Downloaded" tab title,
     ●   click on "Add Plugins..." button,
     ●   choose the directory where the Scala plugins are unzipped,
     ●   select all listed *.nbm files, following the instructions.
●   Set ${SCALA_HOME} or %SCALA_HOME% environment variable
●   Edit ${NETBEANS_HOME}/etc/netbeans.conf
     ●   Add "-J-Dscala.home=/opt/scala" to
         netbeans_default_options
●   More info: http://wiki.netbeans.org/Scala

Recommended for you

HDFS & MapReduce
HDFS & MapReduceHDFS & MapReduce
HDFS & MapReduce

This Hadoop HDFS Tutorial will unravel the complete Hadoop Distributed File System including HDFS Internals, HDFS Architecture, HDFS Commands & HDFS Components - Name Node & Secondary Node. Not only this, even Mapreduce & practical examples of HDFS Applications are showcased in the presentation. At the end, you'll have a strong knowledge regarding Hadoop HDFS Basics. Session Agenda: ✓ Introduction to BIG Data & Hadoop ✓ HDFS Internals - Name Node & Secondary Node ✓ MapReduce Architecture & Components ✓ MapReduce Dataflows ---------- What is HDFS? - Introduction to HDFS The Hadoop Distributed File System provides high-performance access to data across Hadoop clusters. It forms the crux of the entire Hadoop framework. ---------- What are HDFS Internals? HDFS Internals are: 1. Name Node – This is the master node from where all data is accessed across various directores. When a data file has to be pulled out & manipulated, it is accessed via the name node. 2. Secondary Node – This is the slave node where all data is stored. ---------- What is MapReduce? - Introduction to MapReduce MapReduce is a programming framework for distributed processing of large data-sets via commodity computing clusters. It is based on the principal of parallel data processing, wherein data is broken into smaller blocks rather than processed as a single block. This ensures a faster, secure & scalable solution. Mapreduce commands are based in Java. ---------- What are HDFS Applications? 1. Data Mining 2. Document Indexing 3. Business Intelligence 4. Predictive Modelling 5. Hypothesis Testing ---------- Skillspeed is a live e-learning company focusing on high-technology courses. We provide live instructor led training in BIG Data & Hadoop featuring Realtime Projects, 24/7 Lifetime Support & 100% Placement Assistance. Email: sales@skillspeed.com Website: https://www.skillspeed.com

hadoop & mapreducemapreduce in hdfsflume
Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]

「Spark 手把手 - 快速上手營」適合對於想了解如何應用Apache Spark/Hadoop/Kafka來建構大數據資料平台或是處理分析大數據的工程師或工程主管來參加。參加本次活動,參與者都將會有機會體驗 Apache Spark Family 中各項知名的專案,包括 Spark、Spark-SQL、Spark-Streaming、Kafka、HDFS、Parquet、Zeppelin 以及 Java, Scala等工具與技術。 整個活動設計區分為兩大階段: 階段一 Spark應用於批次型資料處理 (Spark for Batch process): 約4週, 每週2小時 階段二 Spark應用於串流式事件處理 (Spark for Streaming process): 約2週, 每週2小時

e2-spk-s01apache sparkspark
Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]

這是Spark手把手的第二個活動[e2-spk-s02] 主要是介紹Spark SQL與DataFrame的應用。 Spark SQL結構化資料處理應用 不同資料結構型態的挑戰 SPARK RDD概念範例#2-進化版 Spark-SQL與DataFrame介詔 Spark-SQL與DataFrame應用範例

spark dataframespark sqleighty20.cc
Tasks (20 min)
●   Run REPL
    ●   Windows: %scala_home%/bin/scala
    ●   Linux: scala or /opt/scala/bin/scala
    ●   Execute a few statements
●   Copy & unpack
    'HeliumPublicCursussenNavorming
    ScalaScalaTraining.zip'
    ●   into 'DocumentenNetbeansProjects' (Windows)
    ●   Into '/home/student/NetbeansProjects' (Linux)
Tasks (20 min)
●   Run unit test in IDE (JUnit 4)
    ●   Open the 'ScalaTraining' project in NetBeans
    ●   Try to compile and test the project (should work)
    ●   scalaexamples.intro.MyFirstTest
         –   Create a failing test
         –   Make it run
●   Make the two classes scalaexamples/intro/HelloWorld.scala
    print “Hello world”. What is the difference?
●   Remove comments from @Test for the methods in
    scalaexamples/intro/CreateStuffTest.scala. Make tests pass.
First class functions
First class functions

val even = Function[Int, Boolean] {
    def apply(i: Int) = i % 2 == 0
}

val even: (Int => Boolean) = (i: Int) => i % 2 == 0
val even = (i: Int) => i % 2 == 0

even.apply(42)       // true
even(13)             // false

Recommended for you

Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]

了解了Spark的基本架構之後, 對大多數的人來說如何可以開始把Spark跟自己的日常資料的處理程序掛上勾。Spark手把手:[e2-spk-s03]著重在體驗如何Spark SQL來處理資料庫的資料以及一些實用的小技巧。 內容包括了: • DataFrame Pivot功能 • Parquet資料格式與Spark的結合 • Spark SQL給合JDBC資訊源 • Spark-SQL/Zeppelin與北風資料庫結合練習

spark dataframeapache zeppelinpivot
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)

Code examples demonstrating Functional Programming concepts, with JavaScript and Haskell. Part 1 can be found here - http://www.slideshare.net/calvinchengx/functional-programming-part01 Source code can be found here - http://github.com/calvinchengx/learnhaskell Let me know if you spot any errors! Thank you! :-)

functional programminghaskelljavascript
Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]

Spark手把手:[e2-spk-s04], 我們要以DevOpts的角度來討論Spark與現有資料處理系統的結合與異同, 同時討論一些在開發、設計、除錯、效能優化及部置Spark程式的相關問題。

spark trainingspark-devopsspark
First class functions
val numbers = List(1, 2, 3, 4, 5)

numbers.filter(even)                // List(2, 4)

numbers.filter((i: Int) => i > 2)   // List(3, 4, 5)
numbers.filter(i => i > 2)          // List(3, 4, 5)
numbers.filter(_ > 2)               // List(3, 4, 5)
Collections


numbers.filter(i =>   i   > 2)   //   List(3, 4, 5)
numbers.find(i => i   >   2)     //   Some(3)
numbers.exists(i =>   i   > 2)   //   true
numbers.forall(i =>   i   > 2)   //   false

numbers.map(i => i * 2)          // List(2, 4, 6, 8, 10)

numbers.foldLeft(0) { (a, b) => a + b }          // 15
Closures

val people = List(Person(“Alf”), Person(“Fredrik”))

var name = “Fredrik”
val nameFilter = (p: Person) => p.name == name

people.filter(nameFilter)     // Person(“Fredrik”)
name = “Alf”
people.filter(nameFilter)     // Person(“Alf”)
Tasks (30 min)
●   Open the 'first-class-functions' project
●   Tests in package
    scalaexamples.firstclassfunctions
●   Add @Test to one and one method
●   Follow instructions in the code
●   Make the tests pass

Recommended for you

Dev Ops Training
Dev Ops TrainingDev Ops Training
Dev Ops Training

The document provides an agenda for a DevOps advanced class on Spark being held in June 2015. The class will cover topics such as RDD fundamentals, Spark runtime architecture, memory and persistence, Spark SQL, PySpark, and Spark Streaming. It will include labs on DevOps 101 and 102. The instructor has over 5 years of experience providing Big Data consulting and training, including over 100 classes taught.

spark summit 2015apache spark
Run Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramRun Your First Hadoop 2.x Program
Run Your First Hadoop 2.x Program

This document provides an overview of Hadoop and related big data technologies. It begins with defining big data and discussing why traditional systems are inadequate. It then introduces Hadoop as a framework for distributed storage and processing of large datasets. The key components of Hadoop - HDFS for storage and MapReduce for processing - are described at a high level. HDFS architecture and read/write operations are outlined. MapReduce paradigm and an example word count job are also summarized. Finally, Hive is introduced as a data warehouse tool built on Hadoop that provides SQL-like queries for large datasets.

hadooptraiing
Getting started with Apache Spark
Getting started with Apache SparkGetting started with Apache Spark
Getting started with Apache Spark

Spark is a fast and general processing engine compatible with Hadoop data. It can run in Hadoop clusters through YARN or Spark's standalone mode, and it can process data in HDFS, HBase, Cassandra, Hive, and any Hadoop InputFormat. It is designed to perform both batch processing (similar to MapReduce) and new workloads like streaming, interactive queries, and machine learning.

spark streamapache sparkspark streaming
Pattern matching
myObject   match {
  case 1   => println("First was hit")
  case 2   => println("Second was Hit")
  case _   => println("Unknown")
}
myObject match {
   case i: Int => println("Found an int")
   case s: String => println("Found a String")
   case _ => println("Unknown")
 }
myObject match {
   case i: Int => println("Found an int")
   case s: String => println("Found a String")
   case other => println("Unknown " + other)
 }

Recommended for you

Spark tutorial py con 2016 part 2
Spark tutorial py con 2016   part 2Spark tutorial py con 2016   part 2
Spark tutorial py con 2016 part 2

Discover insight about car manufacturers from Twitter Data using a Python Notebook connected to Apache Spark

apache sparkdashdbtwitter
Data Science with Spark
Data Science with SparkData Science with Spark
Data Science with Spark

The document outlines an agenda for a conference on Apache Spark and data science, including sessions on Spark's capabilities and direction, using DataFrames in PySpark, linear regression, text analysis, classification, clustering, and recommendation engines using Spark MLlib. Breakout sessions are scheduled between many of the technical sessions to allow for hands-on work and discussion.

data scienceapache sparkanalytics
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)

The document provides an overview of Spark and its machine learning library MLlib. It discusses how Spark uses resilient distributed datasets (RDDs) to perform distributed computing tasks across clusters in a fault-tolerant manner. It summarizes the key capabilities of MLlib, including its support for common machine learning algorithms and how MLlib can be used together with other Spark components like Spark Streaming, GraphX, and SQL. The document also briefly discusses future directions for MLlib, such as tighter integration with DataFrames and new optimization methods.

spark summit 2015apache spark
myObject match {
   case i: Int if i == 1 => println("Found an int")
   case s: String => println("Found a String")
   case other => println("Unknown " + other)
 }
val res = myObject match {
    case i: Int if i == 1 => "Found an int"
    case s: String => "Found a String"
    case other => "Unknown " + other
}
val res = myObject match {
    case (first, second) => second
    case (first, second, third) => third
}
val mathedElement = list match {
  case List(firstElement, lastElement) => lastElement
  case List(firstElement, _ *) => firstElement
  case _ => "failed"
}

Recommended for you

Spark tutorial pycon 2016 part 1
Spark tutorial pycon 2016   part 1Spark tutorial pycon 2016   part 1
Spark tutorial pycon 2016 part 1

This document outlines steps for developing analytic applications using Apache Spark and Python. It covers prerequisites for accessing flight and weather data, deploying a simple data pipe tool to build training, test, and blind datasets, and using an IPython notebook to train predictive models on flight delay data. The agenda includes accessing necessary services on Bluemix, preparing the data, training models in the notebook, evaluating model accuracy, and deploying models.

pythonsparknotebook
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics

This document summarizes key similarities and differences between Scala and Java types, variables, methods, classes, collections, control structures, and other language features. Some of the main points covered include: - Type definitions, variables, and methods are defined similarly but with different syntax in Scala vs Java - Classes and traits in Scala are like classes and interfaces in Java - Scala avoids static methods and instead uses singleton objects - Control structures like if/else, for loops, and exceptions work similarly - Scala supports features like tuples, pattern matching, and expression-oriented programming that have no direct equivalent in Java

Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm

Scala is a powerful language for the JVM that is compatible with JDK 1.5+. It is a functional language maintained by Typesafe along with the community. Scala compiles to JVM bytecode like Java but has features like objects, traits, pattern matching and functional programming. James Gosling, the creator of Java, said that if he were to pick a language other than Java today, it would be Scala.

def length(list: List[_]): Int =
  list match {
    case Nil => 0
    case head :: tail => 1 + length(tail)
  }
public static Integer getSecondOr0(List<Integer> list) {
    if (list != null && list.size() >= 2) {
        return list.get(1);
    } else {
        return 0;
    }
}




def second_or_0(list:List[Int]) = list match {
  case List(_, x, _*) => x
  case _ => 0
}
Case classes
●   Class types that can be used in pattern
    matching
●   Generated into your class:
    ●   equals
    ●   hashCode
    ●   toString
    ●   getters (and optionally setters)
    ●   ++
abstract class Person(name: String)
case class Man(name: String) extends Person(name)
case class Woman(name: String, children: List[Person])
  extends Person(name)

Recommended for you

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala

An overview of the Scala programming language, focusing on differences with Java and in language novelties (in Italian)

scala java introduction trenta3dev
Intro to scala
Intro to scalaIntro to scala
Intro to scala

Scala is a multi-paradigm programming language that runs on the Java Virtual Machine. It is both object-oriented and functional, with support for immutable data and concise syntax. Scala has gained popularity due to its advantages like type safety, concurrency support, and interoperability with Java. However, some of Scala's advanced features can be difficult to read and use for beginners, and tooling support is not as robust as Java. Overall, Scala represents a promising approach that prioritizes simplicity over ease of use.

1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation

The document summarizes Scala as a replacement for Java, highlighting its capabilities as both an object-oriented and functional language that compiles to Java bytecode. It provides code examples demonstrating Scala's concise syntax for common tasks like defining classes, filtering collections, string reversal, and exception handling. The document also outlines an agenda for a Scala workshop covering its basic syntax, REPL/IDE setup, functions, pattern matching, OO features, and functional programming concepts.

p match {
  case Man(name) => println("Man with name " + name)
  case Woman(name, children) => println("Woman with name "
                              + name + " and with " +
                                children.size + " children")
}
val regex = """(d+)(w+)""".r

val myString = ...

val res: String = myString match {
  case regex(digits, word) => digits
  case _ => "None"
}
val regex = """(d+)(w+)""".r

val myString = ...

val res: Option[String] = myString match {
  case regex(digit, word) => Some(digit)
  case _ => None
}
The Option type, never again
           NullPointerException
●   Option has two possible values
    ●   Some(value)
    ●   None



    val someOption: Option[String] = Some("value")
    val noOption:   Option[String] = None

Recommended for you

Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat

The document provides an overview of the Scala programming language. It begins with an agenda that outlines topics like differences between Java and Scala, Scala data types, variables, classes, functions, closures, exception handling and collections. It then discusses specific aspects of Scala like verbosity reduction compared to Java, functional programming influences, object-oriented features, interoperability with Java and compilation to Java bytecode. Examples are provided to illustrate Scala concepts like functions, classes, recursion, higher-order functions and exception handling. The document aims to explain Scala and reasons for differences from Java.

2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one

This document provides a recap of concepts covered on day 1 of a Scala training, including: - How variables, methods, classes, tuples, and the Option type work differently in Scala compared to Java. - Key Scala features like first class functions, closures, pattern matching, and traits. - An overview of the schedule for day 1 which includes higher order functions, implicit conversions, XML support, and building a quiz game task.

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu

The document discusses Scala and why some developers think it could replace Java on the JVM. It provides quotes from several influential developers, including the creator of Java and Groovy, expressing their view that Scala is the best candidate to replace Java in the long run. Specifically, James Gosling says that if he had to pick another language on the JVM besides Java, it would be Scala. Charlie Nutter describes Scala as the current heir apparent to the Java throne and the momentum behind Scala is now unquestionable. James Strachan says that if he had seen the Programming in Scala book in 2003, he may have never created Groovy and that his tip for a long term replacement for Java is

def getValue(s: Any): Option[String]




getValue(object) match {
  case Some(value) => println(value)
  case None => println("Nothing")
}



val result = getValue(object).getOrElse("Nothing")
Tasks (30 min)
●   Open the 'pattern-matching' project
●   Tests in package
    scalaexamples.patternmatching
●   Add @Test to one and one method
●   Follow instructions in the code
●   Make the tests pass
Object orientation and
        traits
Annotations – not marker interfaces


       @serializable class Person

       @SerialVersionUID(1) class Person

       @cloneable class Person

       @remote class Service

Recommended for you

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos

Scala is a general purpose programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It has established itself as one of the main alternative languages on the Java Virtual Machine, being used by companies like Twitter and LinkedIn. Scala fuses functional programming (from which it borrows higher-order functions and closures, generic typing and immutable data structures) and object-oriented programming programming (from which it takes inheritance and encapsulation). It interoperates fully with Java, allowing a smooth transition and access to all existing Java libraries. Scala’s lightweight syntax makes it easy to extend the language through DSLs. In this talk we are going to have a quick overview of Scala’s main features (closures, higher-order functions, implicits), and collection classes in the standard library. We’ll see how a new concurrency model, such as actors, can be added to the language through a library.

genevajugjugscala
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?

Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer. Java som sprog har ikke bevæget sig meget de seneste år. Vi har stadig ikke closures eller funktionelle aspekter som f.eks. C# har haft siden version 3. Er Scala svaret på enhver Javaudviklers bønner eller er sproget kun interessant for tågehoveder som mig, som begynder at synes bedre og bedre om funktionsorientering? Er den store portion syntaktisk sukker, Scala bringer på bordet, bare tomme kalorier?

java scala danish cd10
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?

Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.

scalajavadanish
object
●   object is a “singleton” class
    ●    Call may look like static method calls in Java
    ●    Can inherit from other classes and traits
    ●    Can be passed as a reference

        object MyObject {
          def foo = "bar"
        }

        var baz = MyObject.foo
        val personObject = MyObject
        baz = personObject.foo
Companion object
●   Can read the companion class' private fields
●   Has to be in the same source file

class Person(private val age: Int)

object Person {
  def getPersonAge(p: Person) = p.age
}

val personInstance = new Person(30)
val age = Person.getPersonAge(personInstance)
Magical apply


class Person private(val age: Int)

object Person {
  def apply(age: Int) = new Person(age)
}

var personInstance = Person.apply(30)
    personInstance = Person(30)
Not built in, clever use of apply



val myList = List(1, 2, 3)
val mySet = Set(1, 2, 3)
val myMap = Map(1 -> "one", 2 -> "two")

Recommended for you

BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers

This document provides an introduction to Scala for Java developers. It outlines how Scala cleans up Java syntax by making semi-colons optional, using == for equals and eq for reference equality, and allowing periods to be omitted. It also describes how Scala goes beyond Java by supporting features like case classes, pattern matching, named and default arguments, and mixin composition with traits. The document provides examples of using these features and explains how Scala seamlessly interoperates with Java.

1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics

This document provides a summary of key Scala basics and comparisons to Java, including: 1) It describes type definitions, variables, methods and how they are defined in Scala versus Java. It also covers method invocation syntax differences. 2) It explains classes and constructors, traits versus interfaces, and static methods in Scala versus Java. 3) It provides examples of control structures like if/else, for loops, while loops and exceptions in both languages.

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala

Scala functions provide powerful ways to decompose problems and harness the benefits of functional programming. The presentation introduces core concepts of functional programming using Scala as an example language, highlighting how Scala combines object-oriented and functional programming. It presents benefits like immutability, higher-order functions, and improved concurrency while avoiding past performance issues through modern virtual machines and libraries.

programmingscalafunctional programming
Constructors
●   Always one primary constructor
●   Parameters are automatically instance variables
●   Class “body” is the primary constructors content
●   Auxiliary constructors MUST call or chain to primary
    constructor
    class MyClass(myString: String, myInt: Int)

        val myOtherInt = 10
        println("In main body")

    }
Auxiliary constructors
class MyClass(myString: String, myInt: Int) {

    def this(myString: String) = this(myString, 0)

    def this() = {
      this("foo")
      println("In default constructor")
    }

}
Inheritance


class MyClass(myString: String)

class MySubClass(myString: String, myInt: Int)
      extends MyClass(myString) {

    println("MyString: '" + myString +
            "', MyInt: '" + myInt + "'")

}
Inheritance
●   Single class inheritance
●   Multiple trait mixins

Recommended for you

Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala

This document discusses design patterns in Scala compared to Java. It covers functional interface, command, builder, iterator, template method, strategy, null object, and decorator patterns. The agenda outlines discussing these patterns in part one covering OO patterns. Each pattern section provides a Java example and how it can be implemented in Scala using functions and other Scala features like case classes.

java scala decorator command builder iterator stra
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers

Scala provides many features that simplify programming tasks compared to Java such as type inference, less verbose syntax, simpler definition of classes and collections, closures, pattern matching, implicit conversions, and concise concurrency constructs. However, Scala also has disadvantages like less mature tools compared to Java and lack of binary compatibility between major versions.

javascalasoftshake
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala

This presentation was presented at OSS camp in New Delhi. It deals with the basics of Scala language and how we can use it to build scalable Applications

scala
Syntax


class Person extends AnyRef
             with java.io.Serializable
             with java.rmi.Remote

class Person extends java.io.Serializable
             with java.rmi.Remote
Traits
●   “Multiple inheritance done right”
●   Implement methods
●   Initialized fields
●   Abstract methods
●   Abstract fields
●   Abstract types
●   Does not have constructors
●   Call to super → strict semantics
scala.Ordered trait

trait Ordered[A] {
  def compare(that: A): Int

    def   <    (that:   A):   Boolean   =   (this   compare   that)   <    0
    def   >    (that:   A):   Boolean   =   (this   compare   that)   >    0
    def   <=   (that:   A):   Boolean   =   (this   compare   that)   <=   0
    def   >=   (that:   A):   Boolean   =   (this   compare   that)   >=   0
}
The Ordered trait

class Person(private val age: Int)
      extends Ordered[Person] {

    def compare(other: Person) =
      this.age - other.age
}


val person1 = new Person(21)
val person2 = new Person(31)
person1 < person2 // true
person1 <= person2 // true
person1 >= person2 // false

Recommended for you

Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal

This presentation offers a tutorial for introducing Scala. Readers should be familiar with C++, C# or Java

oopoop 2010scala
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...

Can two JVM languages, none of them Java, work harmoniously, side by side? Should they? In this lecture we’ll see how code written in Groovy and Scala work with Java and how they can be made to work with each other. The lecture is based on the experience of introducing Scala to an actual Groovy project.

groovydinko srkočhujak
Scala - core features
Scala - core featuresScala - core features
Scala - core features

This document provides an introduction to Scala concepts and features compared to Java, including how to set up Scala, the Simple Build Tool (SBT), case classes, lazy definitions, imports, objects, pattern matching, collections, higher-order functions, partial functions, currying, implicit conversions, and implicit parameters. Useful Scala resources are also listed.

“Dynamic mixins”


class Person(age: Int) {
  override def toString = "my age is " + age
}

trait MyTrait {
  override def toString = "I am sure " +
                          super.toString
}

val person = new Person(30) with MyTrait
println(person)

=> I am sure my age is 30
is-a vs has-a
●   Inheritance as usual
●   Easier to implement has-a
●   Inheritance vs composition
Tasks (30 min)
●   Open 'oo-traits' project
●   Tests under scalaexamples
    ●   companionobject
    ●   inheritance
    ●   traits
●   Add @Test to one and one method
●   Follow instructions in code
●   Make tests pass
Functional programming

Recommended for you

Linux troubleshooting tips
Linux troubleshooting tipsLinux troubleshooting tips
Linux troubleshooting tips

Slide deck bij de screencast op https://youtu.be/ciXpmDwJKOM

troubleshootinglinuxsystem administration
Een fileserver opzetten met Samba
Een fileserver opzetten met SambaEen fileserver opzetten met Samba
Een fileserver opzetten met Samba

Slides bij mijn videoles over Samba (zie http://youtu.be/w2RxBkqQ3ZQ)

centoshowtolinux
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheerLinux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer

Dit zijn de slides voor de introductieles van de cursus Enterprise Linux, opleiding ProfBach Toegepaste Informatica, HoGent Bedrijf en Organisatie. Bekijk de opname op http://youtu.be/GGTS37Tsl-M

“Functional programming”
●   First class functions
●   Pattern matching
●   Higher order functions
Functional programming
●   Purity
●   Mathematical functions have no side effects
    ●   f(x) = 2x + 3
    ●   y = sin(x)
●   Mathematical functions always give same result
    for same input
    ●   Only immutable objects (and object graphs)
In practice
●   All fields must be immutable
●   All methods must return something
●   No side-effects from method calls
    ●
        println("...") is also a side effect!
List
●   head :: tail
●   Prepends to the head of the list
●   Other operations (filter, map, remove,
    partition...) returns a new List instance

Recommended for you

A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...

Paper presented at MISTA2013, Gent. In this paper, we present a method based on Learning Automata to solve Hybrid Flexible Flowline Scheduling Problems (HFFSP) with additional constraints like sequence dependent setup times, precedence relations between jobs and machine eligibility. This category of production scheduling problems is noteworthy because it involves several types of constraints that occur in complex real-life production scheduling problems like those in process industry and batch production. In the proposed technique, Learning Automata play a dispersion game to determine the order of jobs to be processed in a way that makespan is minimized, and precedence constraint violations are avoided. Experiments on a set of benchmark problems indicate that this method can yield better results than the ones known until now.

reinforcement learningproduction schedulinglearning automata
Gebruikers, groepen en permissies
Gebruikers, groepen en permissiesGebruikers, groepen en permissies
Gebruikers, groepen en permissies

Slides bij de screencasts gepubliceerd op http://youtu.be/5MfeegzjbSY en http://youtu.be/nt6Ra5E3qLA. Zie daar voor meer uitleg...

Wachtwoorden in Linux
Wachtwoorden in LinuxWachtwoorden in Linux
Wachtwoorden in Linux

Slides bij screencast http://youtu.be/1gmdMSNNo4I. Voor details, zie daar.

scala.collection.immutable
●   ...or scala.collection.mutable
●   Pick your poison!
Scala 2.8
●   Case classes get copy methods
●   Constructors and methods get
    ●   named parameters
        def resize(width: Int, height: Int) = { ... }
        resize(height = 42, width = 120)
    ●   default parameters
        def f(elems: List[Int], x: Int = 0,
              cond: Boolean = true)
        f(List(1))
        f(Nil, cond = false)
Strive to be pure
●   Parallelization and concurrency (no
    synchronization)
●   Usually easier to find errors (a lot less state)
●   Easier to test
Refactoring imperative style code
def printMultiTable () {
  var i = 1 // row
  while (i <= 10) {
    var j = 1 // column
    while (j <= 10) {
      val prod = (i * j).toString
      var k = prod.length // padding
      while (k < 4) {              1    2    3    4    5    6    7    8    9 10
        print(" ")                 2    4    6    8   10   12   14   16   18 20
        k += 1                     3    6    9   12   15   18   21   24   27 30
      }                            4    8   12   16   20   24   28   32   36 40
      print(prod)                  5   10   15   20   25   30   35   40   45 50
      j += 1                       6   12   18   24   30   36   42   48   54 60
                                   7   14   21   28   35   42   49   56   63 70
    }
                                   8   16   24   32   40   48   56   64   72 80
    println()                      9   18   27   36   45   54   63   72   81 90
    i += 1                        10   20   30   40   50   60   70   80   90 100
  }
}

Recommended for you

Een literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waaromEen literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waarom

Hoe zoek je informatie op voor een scriptie, welke tools zijn er om die efficient te verzamelen en bij te houden, hoe verwerk je dit tot een literatuurstudie met bijhorende referentielijst?

Workshop latex
Workshop latexWorkshop latex
Workshop latex

Inleiding op LaTeX: documentstructuur, basiscommando's

latexworkshop
Clean, effective java
Clean, effective javaClean, effective java
Clean, effective java

In deze presentatie die ik gaf aan collega's, licht ik enkele topics toe uit deze boeken: - Robert C. Martin, Clean Code - Joshua Bloch, Effective Java

javabest practiceclean code
Refactoring imperative style code
●   Side effect: printing table
    ●   Functional style: return String
●   Harder to test
    ●   How to test result of println()?
●   While loop & vars
    ●   Functional style: val, for expressions, helper
        functions
    ●   Helper functions can be tested separately
Functional style multiplication table

    def makeRowSeq(row: Int) =
      for (col <- 1 to 10) yield {
        val prod = (row * col).toString
        val padding = " " * (4 - prod.length)
        padding + prod
      }

    def makeRow(row: Int) = makeRowSeq(row).mkString

    def multiTable = {
      val tableSeq =
        for (row <- 1 to 10)
          yield makeRow(row)
      tableSeq.mkString("n")
    }
A closer look at Collections
 ●   Overview of collection traits




http://www.decodified.com/scala/collections-api.xml
Traversable
●    One abstract method:
     def foreach[U](f: Elem => U)
●    50+ concrete methods
      ●   Addition, mapping, conversion, copying, size info,
          element retrieval, sub-collection retrieval,
          subdivision, element tests, folds, string operations,
          view



    http://www.scala-lang.org/api/
    http://www.scala-lang.org/docu/files/collections-api/

Recommended for you

Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptxFinal_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx

MATATAG curriculum training

Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9

In June 2020, L.L. McKinney, a Black author of young adult novels, began the #publishingpaidme hashtag to create a discussion on how the publishing industry treats Black authors: “what they’re paid. What the marketing is. How the books are treated. How one Black book not reaching its parameters casts a shadow on all Black books and all Black authors, and that’s not the same for our white counterparts.” (Grady 2020) McKinney’s call resulted in an online discussion across 65,000 tweets between authors of all races and the creation of a Google spreadsheet that collected information on over 2,000 titles. While the conversation was originally meant to discuss the ethical value of book publishing, it became an economic assessment by authors of how publishers treated authors of color and women authors without a full analysis of the data collected. This paper would present the data collected from relevant tweets and the Google database to show not only the range of advances among participating authors split out by their race, gender, sexual orientation and the genre of their work, but also the publishers’ treatment of their titles in terms of deal announcements and pre-pub attention in industry publications. The paper is based on a multi-year project of cleaning and evaluating the collected data to assess what it reveals about the habits and strategies of American publishers in acquiring and promoting titles from a diverse group of authors across the literary, non-fiction, children’s, mystery, romance, and SFF genres.

book publishing race gender
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx

Chapter 2 Era of One party Dominance Class 12 Political Science Notes

Iterable
●   Abstract method iterator
●   Default implementation of foreach:
    def foreach[U](f:Elem => U): Unit = {
      val it = iterator
      while (it.hasNext) f(it.next())
    }
    ●   Subclasses may override
●   Some concrete methods
    ●   Subcollections, "zippers", comparison
Seq, IndexedSeq, LinearSeq
●   Sequence:
    ●   iterable that has a length,
    ●   elements have fixed index position, starting with 0
●   Operations:
    ●   Indexing (apply), search, addition, update, sorting,
        reversal, comparison, set operations
●   IndexedSeq, LinearSeq
    ●   No new operations, but different performance
         –   LinearSeq: efficient head, tail
         –   IndexedSeq: efficient apply, length
Sets, SortedSet
●   Set = iterable that contain no duplicates
    ●   Operations for tests, addition, removal, set
        operations
●   SortedSet
    ●   Iterator/foreach visit elements in given ordering
    ●   Default implementation: binary tree
Maps
●   Map = collection of pairs of keys and values
    e.g. Map("x" -> 24, "y" -> 25, "z" -> 26)
    ●   Operations for lookup, addition/update, removal,
        subcollections, transformations

Recommended for you

Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...

edu

Split Shifts From Gantt View in the Odoo 17
Split Shifts From Gantt View in the  Odoo 17Split Shifts From Gantt View in the  Odoo 17
Split Shifts From Gantt View in the Odoo 17

Odoo allows users to split long shifts into multiple segments directly from the Gantt view.Each segment retains details of the original shift, such as employee assignment, start time, end time, and specific tasks or descriptions.

gantt viewodoo 17gantt view in odoo
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...

Title: Relational Database Management System Concepts(RDBMS) Description: Welcome to the comprehensive guide on Relational Database Management System (RDBMS) concepts, tailored for final year B.Sc. Computer Science students affiliated with Alagappa University. This document covers fundamental principles and advanced topics in RDBMS, offering a structured approach to understanding databases in the context of modern computing. PDF content is prepared from the text book Learn Oracle 8I by JOSE A RAMALHO. Key Topics Covered: Main Topic : DATA INTEGRITY, CREATING AND MAINTAINING A TABLE AND INDEX Sub-Topic : Data Integrity,Types of Integrity, Integrity Constraints, Primary Key, Foreign key, unique key, self referential integrity, creating and maintain a table, Modifying a table, alter a table, Deleting a table Create an Index, Alter Index, Drop Index, Function based index, obtaining information about index, Difference between ROWID and ROWNUM Target Audience: Final year B.Sc. Computer Science students at Alagappa University seeking a solid foundation in RDBMS principles for academic and practical applications. About the Author: Dr. S. Murugan is Associate Professor at Alagappa Government Arts College, Karaikudi. With 23 years of teaching experience in the field of Computer Science, Dr. S. Murugan has a passion for simplifying complex concepts in database management. Disclaimer: This document is intended for educational purposes only. The content presented here reflects the author’s understanding in the field of RDBMS as of 2024. Feedback and Contact Information: Your feedback is valuable! For any queries or suggestions, please contact muruganjit@agacollege.in

data integritytypes of integrityintegrity constraints
Immutable collections




http://www.decodified.com/scala/collections-api.xml
Mutable collections
Higher order functions
Higher order functions
●   Functions which take functions as parameters
    and/or return functions

Recommended for you

Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies

Ardra Nakshatra, the sixth Nakshatra in Vedic astrology, spans from 6°40' to 20° in the Gemini zodiac sign. Governed by Rahu, the north lunar node, Ardra translates to "the moist one" or "the star of sorrow." Symbolized by a teardrop, it represents the transformational power of storms, bringing both destruction and renewal. About Astro Pathshala Astro Pathshala is a renowned astrology institute offering comprehensive astrology courses and personalized astrological consultations for over 20 years. Founded by Gurudev Sunil Vashist ji, Astro Pathshala has been a beacon of knowledge and guidance in the field of Vedic astrology. With a team of experienced astrologers, the institute provides in-depth courses that cover various aspects of astrology, including Nakshatras, planetary influences, and remedies. Whether you are a beginner seeking to learn astrology or someone looking for expert astrological advice, Astro Pathshala is dedicated to helping you navigate life's challenges and unlock your full potential through the ancient wisdom of Vedic astrology. For more information about their courses and consultations, visit Astro Pathshala.

lal kitab astrologybest astrology coursecourses of astrology
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024

Howe Writing Center - Orientation Summer 2024

Book Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docxBook Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docx

This book for Allied Health Sciences, DPT and BS Nursing for 1st and 2nd semester.

Higher order functions
Short summary of first class functions:
val even: (Int => Boolean) = (i: Int) => i % 2 == 0



Same type definition:
def test(numbers: List[Int], f: Int => Boolean) = ...



Call:
test(List(1, 2, 3), (i: Int) => i % 2 == 0)
Higher order functions

def test(numbers: List[Int],
         f: Int => Boolean) =
  numbers.map(tall => f(tall))


// List[Boolean]
Higher order functions
Functions with several parameters must list them
in parenthesis:


def test(l: List[String],
         f: (Int, String) => Boolean)
call-by-value vs. call-by-name
●   by-value: expressions are evaluated before
    being passed to the function

●   by-name: expressions evaluated inside function
    ●   nice when computationally expensive
    ●   possible to create nice APIs

Recommended for you

ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdfARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf

Verious architectural patterns of tumor cells in histopathology

by dr dharmaraj pawar
Front Desk Management in the Odoo 17 ERP
Front Desk  Management in the Odoo 17 ERPFront Desk  Management in the Odoo 17 ERP
Front Desk Management in the Odoo 17 ERP

Front desk officers are responsible for taking care of guests and customers. Their work mainly involves interacting with customers and business partners, either in person or through phone calls.

front desk in odoo 17odoo 17odoo erp
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases

There are 3 types of inheritance in odoo Classical, Extension, and Delegation. Delegation inheritance is used to sink other models to our custom model. And there is no change in the views. This slide will discuss delegation inheritance and its use cases in odoo 17.

inheritance in odooodoo 17inheritance in odoo 17
call-by-value vs. call-by-name
Example: Logging


def thisTakesTime = {
    println(“Slow computation”)
    “result”
}
logger.debug(thisTakesTime())
call-by-value
def debug(s: String) {
      println(“debug”)
      if (logLevel <= DEBUG) println(s)
}


// Slow computation
// debug
// result
call-by-name
def debug(s: => String) {
      println(“debug”)
      if (logLevel <= DEBUG) println(s)
}


// debug
// Slow computation
// result
BufferedReader reader = null;
try {
  reader = new BufferedReader(new FileReader("f.txt"));
  System.out.println(reader.readLine());
} finally {
  if (reader != null) {
    try {
      reader.close();
    } catch (IOException e) {
      // Exception on close, ignore
    }
  }
}


using(new BufferedReader(new FileReader("f.txt"))) {
  reader => println(reader.readLine())
}

Recommended for you

How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17

Now we can take look into how to configure time off types in odoo 17 through this slide. Time-off types are used to grant or request different types of leave. Only then the authorities will have a clear view or a clear understanding of what kind of leave the employee is taking.

odoo 17time off typestime off types in odoo
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISINGSYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING

 Integrated Marketing Communications (IMC)- Concept, Features, Elements, Role of advertising in IMC  Advertising: Concept, Features, Evolution of Advertising, Active Participants, Benefits of advertising to Business firms and consumers.  Classification of advertising: Geographic, Media, Target audience and Functions.

integrated marketingcommunicationadvertising
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf

we may assume that God created the cosmos to be his great temple, in which he rested after his creative work. Nevertheless, his special revelatory presence did not fill the entire earth yet, since it was his intention that his human vice-regent, whom he installed in the garden sanctuary, would extend worldwide the boundaries of that sanctuary and of God’s presence. Adam, of course, disobeyed this mandate, so that humanity no longer enjoyed God’s presence in the little localized garden. Consequently, the entire earth became infected with sin and idolatry in a way it had not been previously before the fall, while yet in its still imperfect newly created state. Therefore, the various expressions about God being unable to inhabit earthly structures are best understood, at least in part, by realizing that the old order and sanctuary have been tainted with sin and must be cleansed and recreated before God’s Shekinah presence, formerly limited to heaven and the holy of holies, can dwell universally throughout creation

shekinah sanctuary sabbath
def using[T <: { def close() }, A]
         (closeable: T)
         (f: T => A) = {
  try {
    f(closeable)
  } finally {
    if (closeable != null) {
      try {
        closeable.close()
      }
      catch {
        case e: Exception =>
          // Do something clever!?
      }
    }
  }
}
Tasks (30 min)
●   Open 'higher-order-functions' project
●   Tests in scalaexamples.higherorderfunctions
●   Add @Test to one and one method
●   Implement missing functions in PersonFilter
    and so on.
●   Follow instructions in code
●   Make tests pass
Where to go next?
Advanced topics
●   Type inference
●   Implicit conversions
●   Extractors
●   Annotations
●   XML
●   Parallel programming with Actors
●   Domain Specific Languages (DSLs)
●   GUI programming with Scala Swing

Recommended for you

AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894

As artificial intelligence continues to evolve, understanding the complexities and regulations regarding AI risk management is more crucial than ever. Amongst others, the webinar covers: • ISO/IEC 42001 standard, which provides guidelines for establishing, implementing, maintaining, and continually improving AI management systems within organizations • insights into the European Union's landmark legislative proposal aimed at regulating AI • framework and methodologies prescribed by ISO/IEC 23894 for identifying, assessing, and mitigating risks associated with AI systems Presenters: Miriama Podskubova - Attorney at Law Miriama is a seasoned lawyer with over a decade of experience. She specializes in commercial law, focusing on transactions, venture capital investments, IT, digital law, and cybersecurity, areas she was drawn to through her legal practice. Alongside preparing contract and project documentation, she ensures the correct interpretation and application of European legal regulations in these fields. Beyond client projects, she frequently speaks at conferences on cybersecurity, online privacy protection, and the increasingly pertinent topic of AI regulation. As a registered advocate of Slovak bar, certified data privacy professional in the European Union (CIPP/e) and a member of the international association ELA, she helps both tech-focused startups and entrepreneurs, as well as international chains, to properly set up their business operations. Callum Wright - Founder and Lead Consultant Founder and Lead Consultant Callum Wright is a seasoned cybersecurity, privacy and AI governance expert. With over a decade of experience, he has dedicated his career to protecting digital assets, ensuring data privacy, and establishing ethical AI governance frameworks. His diverse background includes significant roles in security architecture, AI governance, risk consulting, and privacy management across various industries, thorough testing, and successful implementation, he has consistently delivered exceptional results. Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment. Date: June 26, 2024 Tags: ISO/IEC 42001, Artificial Intelligence, EU AI Act, ISO/IEC 23894 ------------------------------------------------------------------------------- Find out more about ISO training and certification services Training: ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB Webinars: https://pecb.com/webinars Article: https://pecb.com/article -------------------------------------------------------------------------------

The basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptxThe basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptx

Pie

CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...

https://app.box.com/s/ujmypxg6wegshvv0hmylp5m8hx4dnzrc

Exercises
●   Solutions to exercises:
    http://github.com/javaBin/scala-training-code/zipball/solutions
●   99 Scala Problems:
    http://aperiodic.net/phil/scala/s-99/
Bert's Scala bookmarks:
http://www.delicious.com/bertvv/scala
A lot of blogs




http://www.planetscala.com/
Mailing lists

        scala@listes.epfl.ch
  scala-announce@listes.epfl.ch
     scala-user@listes.epfl.ch
    scala-debate@listes.epfl.ch
     scala-tools@listes.epfl.ch
   scala-internals@listes.epfl.ch

http://www.scala-lang.org/node/199

Recommended for you

"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...

"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY NĂM 2024 KHỐI NGÀNH NGOÀI SƯ PHẠM"

ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM

Curricuum Map in Grade 7 English aligned with matatag

curriculumgrammar
Several books




                         +++
          http://www.scala-lang.org/node/959
Creative Commons




   http://programming-scala.labs.oreilly.com/index.html
http://www.scala-lang.org/
Creative Commons
         Attribution 3.0 Unported

                     Scala Training Code
       http://github.com/javaBin/scala-training-code
  git clone git://github.com/javaBin/scala-training-code



                     Scala Training Slides
       http://github.com/javaBin/scala-training-slides
git clone git://github.com/javaBin/scala-training-slides.git

Recommended for you

More Related Content

What's hot

Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
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
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
Jakub Kahovec
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
Hiroshi Ono
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
akuklev
 

What's hot (17)

Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
All about scala
All about scalaAll about scala
All about scala
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Procedure Typing for Scala
Procedure Typing for ScalaProcedure Typing for Scala
Procedure Typing for Scala
 

Viewers also liked

Scala+RDD
Scala+RDDScala+RDD
Scala+RDD
Yuanhang Wang
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
Chinedu Ekwunife
 
Scala+spark 2nd
Scala+spark 2ndScala+spark 2nd
Scala+spark 2nd
Yuanhang Wang
 
Scala meetup - Intro to spark
Scala meetup - Intro to sparkScala meetup - Intro to spark
Scala meetup - Intro to spark
Javier Arrieta
 
One vagrantfile to rule them all
One vagrantfile to rule them allOne vagrantfile to rule them all
One vagrantfile to rule them all
Bert Van Vreckem
 
Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015
Jongwook Woo
 
NYC_2016_slides
NYC_2016_slidesNYC_2016_slides
NYC_2016_slides
Nathan Halko
 
HDFS & MapReduce
HDFS & MapReduceHDFS & MapReduce
HDFS & MapReduce
Skillspeed
 
Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]
Erhwen Kuo
 
Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]
Erhwen Kuo
 
Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]
Erhwen Kuo
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]
二文 郭
 
Dev Ops Training
Dev Ops TrainingDev Ops Training
Dev Ops Training
Spark Summit
 
Run Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramRun Your First Hadoop 2.x Program
Run Your First Hadoop 2.x Program
Skillspeed
 
Getting started with Apache Spark
Getting started with Apache SparkGetting started with Apache Spark
Getting started with Apache Spark
Habib Ahmed Bhutto
 
Spark tutorial py con 2016 part 2
Spark tutorial py con 2016   part 2Spark tutorial py con 2016   part 2
Spark tutorial py con 2016 part 2
David Taieb
 
Data Science with Spark
Data Science with SparkData Science with Spark
Data Science with Spark
Krishna Sankar
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Spark Summit
 
Spark tutorial pycon 2016 part 1
Spark tutorial pycon 2016   part 1Spark tutorial pycon 2016   part 1
Spark tutorial pycon 2016 part 1
David Taieb
 

Viewers also liked (20)

Scala+RDD
Scala+RDDScala+RDD
Scala+RDD
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Scala+spark 2nd
Scala+spark 2ndScala+spark 2nd
Scala+spark 2nd
 
Scala meetup - Intro to spark
Scala meetup - Intro to sparkScala meetup - Intro to spark
Scala meetup - Intro to spark
 
One vagrantfile to rule them all
One vagrantfile to rule them allOne vagrantfile to rule them all
One vagrantfile to rule them all
 
Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015Spark tutorial @ KCC 2015
Spark tutorial @ KCC 2015
 
NYC_2016_slides
NYC_2016_slidesNYC_2016_slides
NYC_2016_slides
 
HDFS & MapReduce
HDFS & MapReduceHDFS & MapReduce
HDFS & MapReduce
 
Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]Spark手把手:[e2-spk-s01]
Spark手把手:[e2-spk-s01]
 
Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]Spark手把手:[e2-spk-s02]
Spark手把手:[e2-spk-s02]
 
Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]Spark手把手:[e2-spk-s03]
Spark手把手:[e2-spk-s03]
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]Spark手把手:[e2-spk-s04]
Spark手把手:[e2-spk-s04]
 
Dev Ops Training
Dev Ops TrainingDev Ops Training
Dev Ops Training
 
Run Your First Hadoop 2.x Program
Run Your First Hadoop 2.x ProgramRun Your First Hadoop 2.x Program
Run Your First Hadoop 2.x Program
 
Getting started with Apache Spark
Getting started with Apache SparkGetting started with Apache Spark
Getting started with Apache Spark
 
Spark tutorial py con 2016 part 2
Spark tutorial py con 2016   part 2Spark tutorial py con 2016   part 2
Spark tutorial py con 2016 part 2
 
Data Science with Spark
Data Science with SparkData Science with Spark
Data Science with Spark
 
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)Advanced Data Science on Spark-(Reza Zadeh, Stanford)
Advanced Data Science on Spark-(Reza Zadeh, Stanford)
 
Spark tutorial pycon 2016 part 1
Spark tutorial pycon 2016   part 1Spark tutorial pycon 2016   part 1
Spark tutorial pycon 2016 part 1
 

Similar to Workshop Scala

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Lorenzo Dematté
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
wpgreenway
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
futurespective
 
Scala ntnu
Scala ntnuScala ntnu
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
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
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
retronym
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
Radim Pavlicek
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 

Similar to Workshop Scala (20)

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
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?
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Java patterns in Scala
Java patterns in ScalaJava patterns in Scala
Java patterns in Scala
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
Javantura v2 - All Together Now - making Groovy and Scala sing together - Din...
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 

More from Bert Van Vreckem

Linux troubleshooting tips
Linux troubleshooting tipsLinux troubleshooting tips
Linux troubleshooting tips
Bert Van Vreckem
 
Een fileserver opzetten met Samba
Een fileserver opzetten met SambaEen fileserver opzetten met Samba
Een fileserver opzetten met Samba
Bert Van Vreckem
 
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheerLinux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer
Bert Van Vreckem
 
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
Bert Van Vreckem
 
Gebruikers, groepen en permissies
Gebruikers, groepen en permissiesGebruikers, groepen en permissies
Gebruikers, groepen en permissies
Bert Van Vreckem
 
Wachtwoorden in Linux
Wachtwoorden in LinuxWachtwoorden in Linux
Wachtwoorden in Linux
Bert Van Vreckem
 
Een literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waaromEen literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waarom
Bert Van Vreckem
 
Workshop latex
Workshop latexWorkshop latex
Workshop latex
Bert Van Vreckem
 
Clean, effective java
Clean, effective javaClean, effective java
Clean, effective java
Bert Van Vreckem
 

More from Bert Van Vreckem (9)

Linux troubleshooting tips
Linux troubleshooting tipsLinux troubleshooting tips
Linux troubleshooting tips
 
Een fileserver opzetten met Samba
Een fileserver opzetten met SambaEen fileserver opzetten met Samba
Een fileserver opzetten met Samba
 
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheerLinux Enterprise - inleiding cursus, 5 trends in systeembeheer
Linux Enterprise - inleiding cursus, 5 trends in systeembeheer
 
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...
 
Gebruikers, groepen en permissies
Gebruikers, groepen en permissiesGebruikers, groepen en permissies
Gebruikers, groepen en permissies
 
Wachtwoorden in Linux
Wachtwoorden in LinuxWachtwoorden in Linux
Wachtwoorden in Linux
 
Een literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waaromEen literatuurstudie maken: hoe & waarom
Een literatuurstudie maken: hoe & waarom
 
Workshop latex
Workshop latexWorkshop latex
Workshop latex
 
Clean, effective java
Clean, effective javaClean, effective java
Clean, effective java
 

Recently uploaded

Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptxFinal_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
shimeathdelrosario1
 
Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9
John Rodzvilla
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Brajeswar Paul
 
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Zuzana Mészárosová
 
Split Shifts From Gantt View in the Odoo 17
Split Shifts From Gantt View in the  Odoo 17Split Shifts From Gantt View in the  Odoo 17
Split Shifts From Gantt View in the Odoo 17
Celine George
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Murugan Solaiyappan
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Astro Pathshala
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
Elizabeth Walsh
 
Book Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docxBook Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docx
drtech3715
 
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdfARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
DharmarajPawar
 
Front Desk Management in the Odoo 17 ERP
Front Desk  Management in the Odoo 17 ERPFront Desk  Management in the Odoo 17 ERP
Front Desk Management in the Odoo 17 ERP
Celine George
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
Celine George
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
Celine George
 
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISINGSYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
Dr Vijay Vishwakarma
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
JackieSparrow3
 
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
PECB
 
The basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptxThe basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptx
heathfieldcps1
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
Nguyen Thanh Tu Collection
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
thanhluan21
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
HappieMontevirgenCas
 

Recently uploaded (20)

Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptxFinal_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
Final_SD_Session3_Ferriols, Ador Dionisio, Fajardo.pptx
 
Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9Beyond the Advance Presentation for By the Book 9
Beyond the Advance Presentation for By the Book 9
 
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
 
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
Traces of the Holocaust in our communities in Levice Sovakia and Constanta Ro...
 
Split Shifts From Gantt View in the Odoo 17
Split Shifts From Gantt View in the  Odoo 17Split Shifts From Gantt View in the  Odoo 17
Split Shifts From Gantt View in the Odoo 17
 
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
Lecture_Notes_Unit4_Chapter_8_9_10_RDBMS for the students affiliated by alaga...
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
 
Book Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docxBook Allied Health Sciences kmu MCQs.docx
Book Allied Health Sciences kmu MCQs.docx
 
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdfARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
 
Front Desk Management in the Odoo 17 ERP
Front Desk  Management in the Odoo 17 ERPFront Desk  Management in the Odoo 17 ERP
Front Desk Management in the Odoo 17 ERP
 
Delegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use CasesDelegation Inheritance in Odoo 17 and Its Use Cases
Delegation Inheritance in Odoo 17 and Its Use Cases
 
How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17How to Configure Time Off Types in Odoo 17
How to Configure Time Off Types in Odoo 17
 
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISINGSYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
 
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdfThe Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
The Jewish Trinity : Sabbath,Shekinah and Sanctuary 4.pdf
 
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
AI Risk Management: ISO/IEC 42001, the EU AI Act, and ISO/IEC 23894
 
The basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptxThe basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptx
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 12 - GLOBAL SUCCESS - FORM MỚI 2025 - HK1 (C...
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
 

Workshop Scala

  • 1. Scala workshop Created by Fredrik Vraalsen (fredrik@vraalsen.no) and Alf Kristian Støyle (alf.kristian@gmail.com) Adapted Bert Van Vreckem (bert.vanvreckem@hogent.be)
  • 2. If I were to pick a language to use today other than Java, it would be Scala. James Gosling
  • 3. Scala, it must be stated, is the current heir apparent to the Java throne. No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable. Charlies Olivier Nutter - JRuby lead
  • 4. Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy. James Strachen
  • 5. public class Person { private int age; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } } class Person(var age: Int, var name: String)
  • 6. List<Person> persons = ... List<Person> adults = new LinkedList<Person>(); List<Person> kids = new LinkedList<Person>(); for (Person person : persons) { if (person.getAge() < 18) { kids.add(person); } else { adults.add(person); } } val (kids, adults) = persons.partition(_.age < 18)
  • 7. String s = "!em esreveR"; System.out.println(s.reverse()); val s = "!em esreveR" println(s.reverse) => Reverse me!
  • 8. BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("f.txt")); System.out.println(reader.readLine()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Exception on close, ignore } } } using(new BufferedReader(new FileReader("f.txt"))) { reader => println(reader.readLine()) }
  • 9. I will never forget these words: "With great power comes great responsibility." This is my gift, my curse. Who am I? I'm Spider-man.
  • 10. val myList = List(1, 2, 3) val res = (10 /: myList)(_+_) => ??
  • 11. Scala ● Object oriented and functional ● Statically typed ● Java compatible ● Complies to Java bytecode (and CLR) ● Existing libraries/frameworks ● Better Java
  • 12. Todays schedule ● Basic syntax ● REPL, IDEs and setup ● First class functions ● Pattern matching ● OO and traits ● Functional programming ● Higher order functions
  • 14. ;
  • 15. Type definitions Scala Java s: String String s i: Int int i / Integer i
  • 16. Variables Scala: Java: val s = "Hello World" public final String s = "Hello World"; var i = 1 public int i = 1; private var j = 3 private int j = 3;
  • 17. Methods (3) Scala: Java: override def toString = ... @Override public String toString() {...}
  • 18. Classes and constructors Scala: Java: class Person(val name: public class Person { String) private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
  • 19. Traits (= Interface + Mixin) Scala: Java: trait Shape { interface Shape { def area: Double public double area(); } } class Circle extends Object public class Circle extends with Shape Object implements Shape
  • 20. No “static” in Scala Scala: Java: object PersonUtil { public class PersonUtil { val ageLimit = 18 public static final int AGE_LIMIT = 18; def countPersons( public static int persons: List[Person]) = countPersons( ... List<Person> persons) } { ... } }
  • 21. While-loops Scala: Java: while (true) { while (true) { ... ... } }
  • 22. Exceptions Scala: Java: throw new throw new Exception(“...”) Exception(“...”) try { try { } catch { } catch (IOException e) { case e: IOException ... => ... } finally { } finally { } }
  • 23. Varargs def foo(values: String*){ } public void foo(String... values){ } foo("bar", "baz") foo("bar", "baz"); val arr = Array("bar", "baz") String[] arr = new String[]{"bar", "baz"} foo(arr: _*) foo(arr);
  • 24. (Almost) everything is an expression val res = if (foo) x else y val res = for (i <- 1 to 10) yield i // List(1, ..., 10) val res = try { x } catch { ...; y } finally { } // x or y
  • 25. Generics Scala: Java: List[String] List<String>
  • 26. Tuples Scala: Java: val tuple: Tuple2[Int, Pair<Integer, String> tuple String] = = new Pair<Integer, String>(1, “apple”) (1, “apple”) val quadruple = ... yeah right... ;-) (2, “orange”, 0.5d, false)
  • 27. Packages Scala: Java: package mypackage package mypackage; ... ...
  • 28. Imports Scala: Java: import java.util.{List, import java.util.List ArrayList} import java.util.ArrayList import java.io._ import java.io.* import scala.util.Sorting._ ??? import java.sql.{Date => ??? SDate}
  • 29. REPL, IDE and setup
  • 30. REPL: Read-Eval-Print Loop ● Command line shell for on-the-fly execution of Scala statements ● $ cd ${SCALA_HOME}/bin $ scala ● Windows, e.g. C:Program FilesScala 2.8.0 ● Linux, e.g. /opt/scala or /usr/local/scala
  • 31. IDE ● They are all !#$&§? compared to what you are used to with Java support ● Netbeans (very good) but bad in other areas... ● IntelliJ IDEA (pretty good) but slow compilation, bonus community edition is free (with Scala) ● Eclipse (not all that good) but very fast when working
  • 32. Netbeans 6.9.x installation ● Download plugins http://sf.net/projects/erlybird/files/nb-scala/6.9v1.1.0/ ● In NetBeans "Tools" | "Plugins", ● click on "Downloaded" tab title, ● click on "Add Plugins..." button, ● choose the directory where the Scala plugins are unzipped, ● select all listed *.nbm files, following the instructions. ● Set ${SCALA_HOME} or %SCALA_HOME% environment variable ● Edit ${NETBEANS_HOME}/etc/netbeans.conf ● Add "-J-Dscala.home=/opt/scala" to netbeans_default_options ● More info: http://wiki.netbeans.org/Scala
  • 33. Tasks (20 min) ● Run REPL ● Windows: %scala_home%/bin/scala ● Linux: scala or /opt/scala/bin/scala ● Execute a few statements ● Copy & unpack 'HeliumPublicCursussenNavorming ScalaScalaTraining.zip' ● into 'DocumentenNetbeansProjects' (Windows) ● Into '/home/student/NetbeansProjects' (Linux)
  • 34. Tasks (20 min) ● Run unit test in IDE (JUnit 4) ● Open the 'ScalaTraining' project in NetBeans ● Try to compile and test the project (should work) ● scalaexamples.intro.MyFirstTest – Create a failing test – Make it run ● Make the two classes scalaexamples/intro/HelloWorld.scala print “Hello world”. What is the difference? ● Remove comments from @Test for the methods in scalaexamples/intro/CreateStuffTest.scala. Make tests pass.
  • 36. First class functions val even = Function[Int, Boolean] { def apply(i: Int) = i % 2 == 0 } val even: (Int => Boolean) = (i: Int) => i % 2 == 0 val even = (i: Int) => i % 2 == 0 even.apply(42) // true even(13) // false
  • 37. First class functions val numbers = List(1, 2, 3, 4, 5) numbers.filter(even) // List(2, 4) numbers.filter((i: Int) => i > 2) // List(3, 4, 5) numbers.filter(i => i > 2) // List(3, 4, 5) numbers.filter(_ > 2) // List(3, 4, 5)
  • 38. Collections numbers.filter(i => i > 2) // List(3, 4, 5) numbers.find(i => i > 2) // Some(3) numbers.exists(i => i > 2) // true numbers.forall(i => i > 2) // false numbers.map(i => i * 2) // List(2, 4, 6, 8, 10) numbers.foldLeft(0) { (a, b) => a + b } // 15
  • 39. Closures val people = List(Person(“Alf”), Person(“Fredrik”)) var name = “Fredrik” val nameFilter = (p: Person) => p.name == name people.filter(nameFilter) // Person(“Fredrik”) name = “Alf” people.filter(nameFilter) // Person(“Alf”)
  • 40. Tasks (30 min) ● Open the 'first-class-functions' project ● Tests in package scalaexamples.firstclassfunctions ● Add @Test to one and one method ● Follow instructions in the code ● Make the tests pass
  • 42. myObject match { case 1 => println("First was hit") case 2 => println("Second was Hit") case _ => println("Unknown") }
  • 43. myObject match { case i: Int => println("Found an int") case s: String => println("Found a String") case _ => println("Unknown") }
  • 44. myObject match { case i: Int => println("Found an int") case s: String => println("Found a String") case other => println("Unknown " + other) }
  • 45. myObject match { case i: Int if i == 1 => println("Found an int") case s: String => println("Found a String") case other => println("Unknown " + other) }
  • 46. val res = myObject match { case i: Int if i == 1 => "Found an int" case s: String => "Found a String" case other => "Unknown " + other }
  • 47. val res = myObject match { case (first, second) => second case (first, second, third) => third }
  • 48. val mathedElement = list match { case List(firstElement, lastElement) => lastElement case List(firstElement, _ *) => firstElement case _ => "failed" }
  • 49. def length(list: List[_]): Int = list match { case Nil => 0 case head :: tail => 1 + length(tail) }
  • 50. public static Integer getSecondOr0(List<Integer> list) { if (list != null && list.size() >= 2) { return list.get(1); } else { return 0; } } def second_or_0(list:List[Int]) = list match { case List(_, x, _*) => x case _ => 0 }
  • 51. Case classes ● Class types that can be used in pattern matching ● Generated into your class: ● equals ● hashCode ● toString ● getters (and optionally setters) ● ++
  • 52. abstract class Person(name: String) case class Man(name: String) extends Person(name) case class Woman(name: String, children: List[Person]) extends Person(name)
  • 53. p match { case Man(name) => println("Man with name " + name) case Woman(name, children) => println("Woman with name " + name + " and with " + children.size + " children") }
  • 54. val regex = """(d+)(w+)""".r val myString = ... val res: String = myString match { case regex(digits, word) => digits case _ => "None" }
  • 55. val regex = """(d+)(w+)""".r val myString = ... val res: Option[String] = myString match { case regex(digit, word) => Some(digit) case _ => None }
  • 56. The Option type, never again NullPointerException ● Option has two possible values ● Some(value) ● None val someOption: Option[String] = Some("value") val noOption: Option[String] = None
  • 57. def getValue(s: Any): Option[String] getValue(object) match { case Some(value) => println(value) case None => println("Nothing") } val result = getValue(object).getOrElse("Nothing")
  • 58. Tasks (30 min) ● Open the 'pattern-matching' project ● Tests in package scalaexamples.patternmatching ● Add @Test to one and one method ● Follow instructions in the code ● Make the tests pass
  • 60. Annotations – not marker interfaces @serializable class Person @SerialVersionUID(1) class Person @cloneable class Person @remote class Service
  • 61. object ● object is a “singleton” class ● Call may look like static method calls in Java ● Can inherit from other classes and traits ● Can be passed as a reference object MyObject { def foo = "bar" } var baz = MyObject.foo val personObject = MyObject baz = personObject.foo
  • 62. Companion object ● Can read the companion class' private fields ● Has to be in the same source file class Person(private val age: Int) object Person { def getPersonAge(p: Person) = p.age } val personInstance = new Person(30) val age = Person.getPersonAge(personInstance)
  • 63. Magical apply class Person private(val age: Int) object Person { def apply(age: Int) = new Person(age) } var personInstance = Person.apply(30) personInstance = Person(30)
  • 64. Not built in, clever use of apply val myList = List(1, 2, 3) val mySet = Set(1, 2, 3) val myMap = Map(1 -> "one", 2 -> "two")
  • 65. Constructors ● Always one primary constructor ● Parameters are automatically instance variables ● Class “body” is the primary constructors content ● Auxiliary constructors MUST call or chain to primary constructor class MyClass(myString: String, myInt: Int) val myOtherInt = 10 println("In main body") }
  • 66. Auxiliary constructors class MyClass(myString: String, myInt: Int) { def this(myString: String) = this(myString, 0) def this() = { this("foo") println("In default constructor") } }
  • 67. Inheritance class MyClass(myString: String) class MySubClass(myString: String, myInt: Int) extends MyClass(myString) { println("MyString: '" + myString + "', MyInt: '" + myInt + "'") }
  • 68. Inheritance ● Single class inheritance ● Multiple trait mixins
  • 69. Syntax class Person extends AnyRef with java.io.Serializable with java.rmi.Remote class Person extends java.io.Serializable with java.rmi.Remote
  • 70. Traits ● “Multiple inheritance done right” ● Implement methods ● Initialized fields ● Abstract methods ● Abstract fields ● Abstract types ● Does not have constructors ● Call to super → strict semantics
  • 71. scala.Ordered trait trait Ordered[A] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 }
  • 72. The Ordered trait class Person(private val age: Int) extends Ordered[Person] { def compare(other: Person) = this.age - other.age } val person1 = new Person(21) val person2 = new Person(31) person1 < person2 // true person1 <= person2 // true person1 >= person2 // false
  • 73. “Dynamic mixins” class Person(age: Int) { override def toString = "my age is " + age } trait MyTrait { override def toString = "I am sure " + super.toString } val person = new Person(30) with MyTrait println(person) => I am sure my age is 30
  • 74. is-a vs has-a ● Inheritance as usual ● Easier to implement has-a ● Inheritance vs composition
  • 75. Tasks (30 min) ● Open 'oo-traits' project ● Tests under scalaexamples ● companionobject ● inheritance ● traits ● Add @Test to one and one method ● Follow instructions in code ● Make tests pass
  • 77. “Functional programming” ● First class functions ● Pattern matching ● Higher order functions
  • 78. Functional programming ● Purity ● Mathematical functions have no side effects ● f(x) = 2x + 3 ● y = sin(x) ● Mathematical functions always give same result for same input ● Only immutable objects (and object graphs)
  • 79. In practice ● All fields must be immutable ● All methods must return something ● No side-effects from method calls ● println("...") is also a side effect!
  • 80. List ● head :: tail ● Prepends to the head of the list ● Other operations (filter, map, remove, partition...) returns a new List instance
  • 81. scala.collection.immutable ● ...or scala.collection.mutable ● Pick your poison!
  • 82. Scala 2.8 ● Case classes get copy methods ● Constructors and methods get ● named parameters def resize(width: Int, height: Int) = { ... } resize(height = 42, width = 120) ● default parameters def f(elems: List[Int], x: Int = 0, cond: Boolean = true) f(List(1)) f(Nil, cond = false)
  • 83. Strive to be pure ● Parallelization and concurrency (no synchronization) ● Usually easier to find errors (a lot less state) ● Easier to test
  • 84. Refactoring imperative style code def printMultiTable () { var i = 1 // row while (i <= 10) { var j = 1 // column while (j <= 10) { val prod = (i * j).toString var k = prod.length // padding while (k < 4) { 1 2 3 4 5 6 7 8 9 10 print(" ") 2 4 6 8 10 12 14 16 18 20 k += 1 3 6 9 12 15 18 21 24 27 30 } 4 8 12 16 20 24 28 32 36 40 print(prod) 5 10 15 20 25 30 35 40 45 50 j += 1 6 12 18 24 30 36 42 48 54 60 7 14 21 28 35 42 49 56 63 70 } 8 16 24 32 40 48 56 64 72 80 println() 9 18 27 36 45 54 63 72 81 90 i += 1 10 20 30 40 50 60 70 80 90 100 } }
  • 85. Refactoring imperative style code ● Side effect: printing table ● Functional style: return String ● Harder to test ● How to test result of println()? ● While loop & vars ● Functional style: val, for expressions, helper functions ● Helper functions can be tested separately
  • 86. Functional style multiplication table def makeRowSeq(row: Int) = for (col <- 1 to 10) yield { val prod = (row * col).toString val padding = " " * (4 - prod.length) padding + prod } def makeRow(row: Int) = makeRowSeq(row).mkString def multiTable = { val tableSeq = for (row <- 1 to 10) yield makeRow(row) tableSeq.mkString("n") }
  • 87. A closer look at Collections ● Overview of collection traits http://www.decodified.com/scala/collections-api.xml
  • 88. Traversable ● One abstract method: def foreach[U](f: Elem => U) ● 50+ concrete methods ● Addition, mapping, conversion, copying, size info, element retrieval, sub-collection retrieval, subdivision, element tests, folds, string operations, view http://www.scala-lang.org/api/ http://www.scala-lang.org/docu/files/collections-api/
  • 89. Iterable ● Abstract method iterator ● Default implementation of foreach: def foreach[U](f:Elem => U): Unit = { val it = iterator while (it.hasNext) f(it.next()) } ● Subclasses may override ● Some concrete methods ● Subcollections, "zippers", comparison
  • 90. Seq, IndexedSeq, LinearSeq ● Sequence: ● iterable that has a length, ● elements have fixed index position, starting with 0 ● Operations: ● Indexing (apply), search, addition, update, sorting, reversal, comparison, set operations ● IndexedSeq, LinearSeq ● No new operations, but different performance – LinearSeq: efficient head, tail – IndexedSeq: efficient apply, length
  • 91. Sets, SortedSet ● Set = iterable that contain no duplicates ● Operations for tests, addition, removal, set operations ● SortedSet ● Iterator/foreach visit elements in given ordering ● Default implementation: binary tree
  • 92. Maps ● Map = collection of pairs of keys and values e.g. Map("x" -> 24, "y" -> 25, "z" -> 26) ● Operations for lookup, addition/update, removal, subcollections, transformations
  • 96. Higher order functions ● Functions which take functions as parameters and/or return functions
  • 97. Higher order functions Short summary of first class functions: val even: (Int => Boolean) = (i: Int) => i % 2 == 0 Same type definition: def test(numbers: List[Int], f: Int => Boolean) = ... Call: test(List(1, 2, 3), (i: Int) => i % 2 == 0)
  • 98. Higher order functions def test(numbers: List[Int], f: Int => Boolean) = numbers.map(tall => f(tall)) // List[Boolean]
  • 99. Higher order functions Functions with several parameters must list them in parenthesis: def test(l: List[String], f: (Int, String) => Boolean)
  • 100. call-by-value vs. call-by-name ● by-value: expressions are evaluated before being passed to the function ● by-name: expressions evaluated inside function ● nice when computationally expensive ● possible to create nice APIs
  • 101. call-by-value vs. call-by-name Example: Logging def thisTakesTime = { println(“Slow computation”) “result” } logger.debug(thisTakesTime())
  • 102. call-by-value def debug(s: String) { println(“debug”) if (logLevel <= DEBUG) println(s) } // Slow computation // debug // result
  • 103. call-by-name def debug(s: => String) { println(“debug”) if (logLevel <= DEBUG) println(s) } // debug // Slow computation // result
  • 104. BufferedReader reader = null; try { reader = new BufferedReader(new FileReader("f.txt")); System.out.println(reader.readLine()); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Exception on close, ignore } } } using(new BufferedReader(new FileReader("f.txt"))) { reader => println(reader.readLine()) }
  • 105. def using[T <: { def close() }, A] (closeable: T) (f: T => A) = { try { f(closeable) } finally { if (closeable != null) { try { closeable.close() } catch { case e: Exception => // Do something clever!? } } } }
  • 106. Tasks (30 min) ● Open 'higher-order-functions' project ● Tests in scalaexamples.higherorderfunctions ● Add @Test to one and one method ● Implement missing functions in PersonFilter and so on. ● Follow instructions in code ● Make tests pass
  • 107. Where to go next?
  • 108. Advanced topics ● Type inference ● Implicit conversions ● Extractors ● Annotations ● XML ● Parallel programming with Actors ● Domain Specific Languages (DSLs) ● GUI programming with Scala Swing
  • 109. Exercises ● Solutions to exercises: http://github.com/javaBin/scala-training-code/zipball/solutions ● 99 Scala Problems: http://aperiodic.net/phil/scala/s-99/
  • 111. A lot of blogs http://www.planetscala.com/
  • 112. Mailing lists scala@listes.epfl.ch scala-announce@listes.epfl.ch scala-user@listes.epfl.ch scala-debate@listes.epfl.ch scala-tools@listes.epfl.ch scala-internals@listes.epfl.ch http://www.scala-lang.org/node/199
  • 113. Several books +++ http://www.scala-lang.org/node/959
  • 114. Creative Commons http://programming-scala.labs.oreilly.com/index.html
  • 116. Creative Commons Attribution 3.0 Unported Scala Training Code http://github.com/javaBin/scala-training-code git clone git://github.com/javaBin/scala-training-code Scala Training Slides http://github.com/javaBin/scala-training-slides git clone git://github.com/javaBin/scala-training-slides.git