I used these slides for a Scala workshop that I gave. They are based on these: http://www.scala-lang.org/node/4454. Thanks to Alf Kristian Støyle and Fredrik Vraalsen for sharing!
The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
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
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
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?
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.
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.
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.
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/
Some notes about programming in Scala: it covers Scala syntax and semantics, programming techniques, idioms, patterns. Many Scala features are introduced, from basic to intermediate and advanced. These are not introductory notes, but they assume a working knowledge with some other programming language (Java, C#, C++), object-oriented programming (OOP) concepts, and functional programming (FP) concepts.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
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
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
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?
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.
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.
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.
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/
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
Functional Programming for OO Programmers (part 2)Calvin Cheng
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! :-)
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.
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.
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?
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.
Qcon2011 functions rockpresentation_scalaMichael Stal
This is the part I of the tutorial I planned to give at QCon 2011 on Functional Programming with Scala. It also includes Scala 2.8 as well as upcoming features
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
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.
Linux Enterprise - inleiding cursus, 5 trends in systeembeheerBert Van Vreckem
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
A Reinforcement Learning Approach for Hybrid Flexible Flowline Scheduling Pro...Bert Van Vreckem
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.
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?
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
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
MATATAG CURRICULUM: ASSESSING THE READINESS OF ELEM. PUBLIC SCHOOL TEACHERS I...NelTorrente
In this research, it concludes that while the readiness of teachers in Caloocan City to implement the MATATAG Curriculum is generally positive, targeted efforts in professional development, resource distribution, support networks, and comprehensive preparation can address the existing gaps and ensure successful curriculum implementation.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
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!
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;
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)
} {
...
}
}
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
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"
}
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")
}
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
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
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
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
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
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