This document provides a taxonomy of Scala concepts including object-oriented features, pattern matching, functional programming, actors, futures, implicits, type theory, macros, and category theory. It aims to serve as a reference for many of the terms used in the Scala community. The document covers topics such as case classes, lazy definitions, imports, objects, tuples, pattern matching examples, immutable collections, higher order functions, parallel collections, partial functions, currying, actors, futures, implicit conversions, implicit parameters, implicit classes, type inference, type classes, higher kinded types, algebraic data types, macros, concepts and arrows in category theory, morphisms, and functors.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Slides from my talk at the Feb 2011 Seattle Tech Startups meeting. More info here (along with powerpoint slides): http://www.startupmonkeys.com/2011/02/scala-frugal-mechanic/
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
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.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
Slides from my talk at the Feb 2011 Seattle Tech Startups meeting. More info here (along with powerpoint slides): http://www.startupmonkeys.com/2011/02/scala-frugal-mechanic/
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
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.
In this presentation, You will get to know about Function Literal,Higher Order Function,Partial Function,Partial Applied Function,Nested Function,Closures.
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.
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.
In this presentation, You will get to know about Function Literal,Higher Order Function,Partial Function,Partial Applied Function,Nested Function,Closures.
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.
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 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.
Spring Day | Spring and Scala | Eberhard WolffJAX London
2011-10-31 | 09:45 AM - 10:30 AM
Spring is widely used in the Java world - but does it make any sense to combine it with Scala? This talk gives an answer and shows how and why Spring is useful in the Scala world. All areas of Spring such as Dependency Injection, Aspect-Oriented Programming and the Portable Service Abstraction as well as Spring MVC are covered.
BASE Meetup: "Analysing Scala Puzzlers: Essential and Accidental Complexity i...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at the Boston Area Scala Enthusiasts meetup, by Andrew Phillips & Nermin Serifovic. See http://www.meetup.com/boston-scala/events/228136405/
Scala Up North: "Analysing Scala Puzzlers: Essential and Accidental Complexit...Andrew Phillips
Slides from the presentation "Analysing Scala Puzzlers: Essential and Accidental Complexity in Scala" at Scala Up North 2015, by Andrew Phillips & Nermin Serifovic. See http://scalaupnorth.com/speakers.html#andrew
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
20160609 nike techtalks reactive applications tools of the tradeshinolajla
An update to my talk about concurrency abstractions, including event loops (node.js and Vert.x), CSP (Go, Clojure), Futures, CPS/Dataflow (RxJava) and Actors (Erlang, Akka)
Reactive applications tools of the trade huff poshinolajla
A description of what makes Reactive an important term in developing today's enterprise applications, and a discussion of various tools that support Reactive, including node.js, Go, RxJava, Futures and Actors.
Jamie Allen, Björn Antonsson and Patrik Nordwall discuss patterns of building Akka systems, including the Sentinel for handling failure above a supervisor, flow control and distributed workers. Patrik also built a template for Typesafe Activator v0.2.1 allowing you to try out this distributed workers pattern on your own machine.
There are several frameworks across languages and platforms of Actors, including Erlang, Fantom, Java and Scala. As developers have built systems using these frameworks, patterns of use have begun to emerge that represent "Best Practices" for actor-based systems. In this talk, we will review such patterns, focusing primarily on how to implement them using the Akka framework and Scala.
Caches are used in many layers of applications that we develop today, holding data inside or outside of your runtime environment, or even distributed across multiple platforms in data fabrics. However, considerable performance gains can often be realized by configuring the deployment platform/environment and coding your application to take advantage of the properties of CPU caches.
In this talk, we will explore what CPU caches are, how they work and how to measure your JVM-based application data usage to utilize them for maximum efficiency. We will discuss the future of CPU caches in a many-core world, as well as advancements that will soon arrive such as HP's Memristor.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
5. How I Write Programs
• Pre-Scala:
– Make it work
– Make it work well
– Make it work fast
• With Scala:
– Make it work and work well
– Make it work fast
7. Case Classes
case class Person(firstName: String = "Jamie",
lastName: String = "Allen")
val jamieDoe = Person(lastName = "Doe")
res0: Person = Person(Jamie,Doe)
• Data Transfer Objects (DTOs) done right
• By default, class arguments are immutable & public
• Should never be extended
• Provide equals(), copy(), hashCode() and toString()
implementations
• Don’t have to use new keyword to create instances
• Named Parameters and Default arguments give us Builder pattern
semantics
8. Lazy Definitions
lazy val calculatedValue = piToOneMillionDecimalPoints()
• Excellent for deferring expensive operations
until they are needed
• Reducing initial footprint
• Resolving ordering issues
• Implemented with a guard field and
synchronization, ensuring it is created when
necessary
9. Imports
import scala.collection.immutable.Map
class Person(val fName: String, val lName: String) {
import scala.collection.mutable.{Map => MMap}
val cars: MMap[String, String] = MMap()
...
}
• Can be anywhere in a class
• Allow for selecting multiple classes from a package or
using wildcards
• Aliasing
• Order matters!
10. Objects
object Bootstrapper extends App { Person.createJamieAllen }
object Person {
def createJamieAllen = new Person("Jamie", "Allen")
def createJamieDoe = new Person("Jamie", "Doe")
val aConstantValue = "A constant value”
}
class Person(val firstName: String, val lastName: String)
• Singletons within a JVM process
• No private constructor histrionics
• Companion Objects, used for factories and constants
11. The apply() method
Array(1, 2, 3)
res0: Array[Int] = Array(1, 2, 3)
res0(1)
res1: Int = 2
• In companion objects, it defines default
behavior if no method is called on it
• In a class, it defines the same thing on an
instance of the class
12. Tuples
def firstPerson = (1, Person(firstName = “Barbara”))
val (num: Int, person: Person) = firstPerson
• Binds you to an implementation
• Great way to group values without a DTO
• How to return multiple values, but wrapped in
a single instance that you can bind to specific
values
14. Pattern Matching Examples
name match {
case "Lisa" => println("Found Lisa”)
case Person("Bob") => println("Found Bob”)
case "Karen" | "Michelle" => println("Found Karen or Michelle”)
case Seq("Dave", "John") => println("Got Dave before John”)
case Seq("Dave", "John", _*) => println("Got Dave before John”)
case ("Susan", "Steve") => println("Got Susan and Steve”)
case x: Int if x > 5 => println("got value greater than 5: " + x)
case x => println("Got something that wasn't an Int: " + x)
case _ => println("Not found”)
}
• A gateway drug for Scala
• Extremely powerful and readable
• Not compiled down to lookup/table switch unless
you use the @switch annotation,
17. Referential Transparency
// Transparent
val example1 = "jamie".reverse
val example2 = example1.reverse
println(example1 + example2) // eimajjamie
// Opaque
val example1 = new StringBuffer("Jamie").reverse
val example2 = example1.reverse
println(example1 append example2) // jamiejamie
• An expression is transparent if it can be replaced by its
VALUE without changing the behavior of the program
• In math, all functions are referentially transparent
18. Scala Collections
val myMap = Map(1 -> "one", 2 -> "two", 3 -> "three")
val mySet = Set(1, 4, 2, 8)
val myList = List(1, 2, 8, 3, 3, 4)
val myVector = Vector(1, 2, 3...)
• You have the choice of mutable or immutable
collection instances, immutable by default
• Rich implementations, extremely flexible
19. Rich Collection Functionality
val numbers = 1 to 20 // Range(1, 2, 3, ... 20)
numbers.head // Int = 1
numbers.tail // Range(2, 3, 4, ... 20)
numbers.take(5) // Range(1, 2, 3, 4, 5)
numbers.drop(5) // Range(6, 7, 8, ... 20)
• There are many methods available to you in
the Scala collections library
• Spend 5 minutes every day going over the
ScalaDoc for one collection class
20. Higher Order Functions
val names = List("Barb", "May", "Jon")
names map(_.toUpperCase)
res0: List[java.lang.String] = List(BARB, MAY, JON)
• Really methods in Scala
• Applying closures to collections
21. Higher Order Functions
val names = List("Barb", "May", "Jon")
names map(_.toUpperCase)
res0: List[java.lang.String] = List(BARB, MAY, JON)
names flatMap(_.toUpperCase)
res1: List[Char] = List(B, A, R, B, M, A, Y, J, O, N)
names filter (_.contains("a"))
res2: List[java.lang.String] = List(Barb, May)
val numbers = 1 to 20 // Range(1, 2, 3, ... 20)
numbers.groupBy(_ % 3)
res3: Map[Int, IndexedSeq[Int]] = Map(1 -> Vector(1, 4, 7, 10, 13,
16, 19), 2 -> Vector(2, 5, 8, 11, 14, 17, 20), 0 -> Vector(3, 6, 9,
12, 15, 18))
22. For Comprehensions
val myNums = 1 to 20
for (i <- myNums) yield i + 1
myNums map(_ + 1)
for {
i <- myNums
j <- 1 to i
} yield i * j
myNums flatMap(i => 1 to i map (j => i * j))
• Used for composing higher-order functions
• As you chain higher-order functions, you may
find it easier to reason about them this way
23. Parallel Collections
scala> 1 to 1000000
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3,...
scala> res0.par
res1: s.c.parallel.immutable.ParRange = ParRange(1, 2, 3,...
scala> res1 map(_ + 1)
res2: s.c.parallel.immutable.ParSeq[Int] = ParVector(2, 3, 4,...
scala> res2.seq
res3: s.c.immutable.Range = Range(2, 3, 4,...
• You can easily parallelize the application of a function literal to your
collection by calling the par() method on a collection instance
• Uses JSR166 under the covers to fork/join for you
• Use the seq() method on the parallel collection to return to a
non-parallel instance
24. Partial Functions
class MyActor extends Actor {
def receive = {
case s: String => println("Got a String: " + s)
case i: Int => println("Got an Int: " + i)
case x => println("Got something else: " + x)
}
}
• A simple match without the match keyword
• The receive block in Akka actors is an excellent
example
• Is characterized by what "isDefinedAt" in the
case statements
25. Currying
def product(i: Int)(j: Int) = i * j
val doubler = product(2)_
doubler(3) // Int = 6
doubler(4) // Int = 8
val tripler = product(3)_
tripler(4) // Int = 12
tripler(5) // Int = 15
• Take a function that takes n parameters as separate argument lists
• “Curry” it to create a new function that only takes one parameter
• Fix on a value and use it to apply a specific implementation of a
product with semantic value
• Have to be defined explicitly as such in Scala
• The _ is what explicitly marks this as curried
27. Actors
import akka.actor._
class MyActor extends Actor {
def receive = {
case x => println(“Got value: “ + x)
}
}
• Based on concepts from Erlang/OTP
• Akka is replacing the core language actors
• Concurrency paradigm using networks of
independent objects that only communicate
via messaging and mailboxes
29. Futures
import scala.concurrent._
val costInDollars = Future {
webServiceProxy.getCostInDollars.mapTo[Int]
}
costInDollars map (myPurchase.setCostInDollars(_))
• Allows you to write asynchronous code, which
can be more performant than blocking
• Are not typed, hence the mapTo call above
30. Futures in Sequence
val customerPurchases = for (
costUSD <- Future{ proxy.getCostInDollars.mapTo[Int]}
totalPurchase <- Future{ proxy.addToTotal(costUSD).mapTo[Int]}
} yield ((customerId -> totalPurchase))
• Scala’s for comprehensions allow you to
compose higher-order functions, including
Futures
• By sequencing the expressions on multiple
lines, you can order dependencies
31. Futures in Parallel
val costUSD = Future{proxy.getCostInUSD(cost).mapTo[Int]}
val costCAD = Future{proxy.getCostInCAD(cost).mapTo[Int]}
val combinedCosts = for {
cUSD <- costUSD
cCAD <- costCAD
} yield (cUSD, cCAD)
val costs = for (
(costUSD, costCAD) <-
Future{proxy.getCostInUSD(cost).mapTo[Int]} zip
Future{proxy.getCostInCAD(cost).mapTo[Int]}
} yield (costUSD, costCAD)
• Define the futures separately and then compose
• Alternatively, the zip method allows you to
parallelize futures execution within a for
comprehension
34. Implicit Conversions
case class Person(firstName: String, lastName: String)
implicit def PersonToInt(p: Person) = p.toString.head.toInt
val me = Person("Jamie", "Allen")
val weird = 1 + me
res0: Int = 81
• Looks for definitions at compile time that will
satisfy type incompatibilities
• Modern IDEs will warn you with an underline
when they are in use
• Limit scope as much as possible (see Josh
Suereth's NE Scala 2011)
35. Implicit Parameters
def executeFutureWithTimeout(f: Future)(implicit t: Timeout)
implicit val t: Timeout = Timeout(20, TimeUnit.MILLISECONDS)
executeFutureWithTimeout(Future {proxy.getCustomer(id)})
• Allow you to define default parameter values
that are only overridden if you do so explicitly
• Handy to avoid code duplication
36. Implicit Classes
implicit class Person(name: String)
class Person(name: String)
implicit final def Person(name: String): Person = new Person(name)
• New to Scala 2.10
• Create extension methods to existing types
• Desugars at compile time into a class
definition with an implicit conversion
38. Type Inference
• Declaring a variable/value
• Return types of methods/functions
• See Daniel Spiewak's Philly ETE 2011 talk
• Good idea to show types on public interfaces
• Specify types when you want to type certainty
39. Type Classes I
case class Customer(id: Long, firstName: String, lastName: String)
trait CustomerOrderById extends Ordering[Customer] {
def compare(x: Customer, y: Customer): Int = { ... }
}
implicit object CustomerIdSort extends CustomerOrderById
val customers = List(Customer(1, "Jamie", "Allen"), Customer(5,
"John", "Doe"), Customer(2, "Jane", "Smith"))
val sortedCustomers = customers.sorted(CustomerIdSort)
sortedCustomers: List[Customer] = List(Customer(1,Jamie,Allen),
Customer(2,Jane,Smith), Customer(5,John,Doe))
• Allow you to layer in varying implementations
of behavior without changing an existing
inheritance structure
40. Type Classes II
case class Dog(name: String)
case class Ferret(name: String)
case class Cat(name: String)
abstract class OkayPets[T]
object OkayPets {
implicit object OkayDog extends OkayPets[Dog]
implicit object OkayFerret extends OkayPets[Ferret]
}
def getPet[T](t: T)(implicit p: OkayPets[T]) = t
val myDog = getPet(Dog("Sparky")) // Works
val myCat = getPet(Cat("Sneezy")) // Fails at compile time
• Allows you to generalize types that are
acceptable parameters for methods
41. Higher Kinded Types
Map[A, B] // Type constructor, not a type!
val myMap = Map[Int, String]() // Now it’s a type!
• Use other types to construct a new type
• Also called type constructors
42. Algebraic Data Types
sealed abstract class DayOfTheWeek
case object Sunday extends DayOfTheWeek
case object Monday extends DayOfTheWeek
...
case object Saturday extends DayOfTheWeek
val nextDay(d: DayOfTheWeek): DayOfTheWeek = d match {
case Sunday => Monday
case Monday => Tuesday
...
case Saturday => Sunday
}
}
• Allow you to model the world in finite terms, such as enumerations, but
also define behavior around them, with all of the power of case classes
• A finite number of possible subtypes, enforced by the "sealed" keyword
(must be defined in the same source file)
44. Macros
• New to Scala 2.10
• Macros are used for generating code at
compile time, similar to LISP macros
• Does not have compiler pragmas such as
#ifdef
• Are implemented as "hygenic" macros at the
point you call reify() – identifiers cannot
be closed over in a macro definition
45. ScalaLogging Macro
def debug(message: String): Unit = macro LoggerMacros.debug
private object LoggerMacros {
def debug(c: LoggerContext)(message: c.Expr[String]) = c.universe.reify(
if (c.prefix.splice.underlying.isDebugEnabled)
c.prefix.splice.underlying.debug(message.splice)
)
}
import com.typesafe.scalalogging.Logging
class MyClass extends Logging {
logger.debug("This won't occur if debug is not defined")
}
• Existing log libraries allow us to define logging statements and then
determine whether they result in output at runtime
• ScalaLogging allows a user to use a logging facility but decide at compile
time whether or not to include the logging statement based on log level.
48. Concepts and Arrows
val myIntToStringArrow: Int => String = _.toString
myIntToStringArrow(1100)
res0: String = 1100
• Concepts are types
• Arrows are functions that convert one concept
to another
49. Morphism
val number = 1000
val numericString = number.toString
• Morphisms change one value in a category to
another in the same category, from one type
to another where types are the category
• Simplified, it converts a type with one
property to a type with another property
• Must be pure, not side-effecting
50. Functor
val numbers = List(1, 2, 3, 4)
val numericStrings = numbers.map(_.toString)
• Functors are transformations from one
category to another that preserve morphisms
• Simplified, converts a type from one to
another while maintaining the conversion of a
type with one property to a type with another
property
51. Monad
val customerPurchases = for (
costUSD <- proxy.getCostInDollars
totalPurchase <- proxy.addToTotal(costUSD)
} yield ((customerId -> totalPurchase))
• Very ephemeral concept
• Must meet the laws of a monad to be one
• Combine functor applications because they can be
bound together, sequencing operations on the
underlying types
• flatMap() is the method the Scala compiler uses to
bind monads
53. Credits
• Sources
– Fast Track to Scala courseware by Typesafe
– Scala in Depth, by Josh Suereth
– DSLs in Action, Debasish Ghosh
– Wikipedia
– Runar Bjarnason's NE Scala 2011 talk
– Daniel Sobral's blog
– Brendan McAdams' blog
• Contributors
– Dave Esterkin, Chariot Solutions
– Josh Suereth, Typesafe
Editor's Notes
When you walk out of this room, your head should hurt. But that’s a GOOD thing – the problem is not that these concepts are difficult to grasp, but that you have to understand the vocabulary to even sit in the room with someone discussing them. I want to provide you with a reference point from which you can do your own investigation of what these concepts mean.
Ask why we don’t need the “new” keyword with case classes
Very fragile
Constant, Constructor, Or, Sequence, Sequence with wildcard, tuple, typed with guard, bound variable wildcard, wildcardBy definition, a lookup/table switch on the JVM can only be an int or enumerated type. Tell the story about your implementation of a jump table using hashes of class definitions – 5000 of them, had to do some delegation due to max method size on the JVM, but was able to perform the deepest match in ~300ns
Very powerful programming paradigmInverts imperative logic - apply your idempotent function to your dataThis is NOT monads, functors and the like, despite what you will hear in the communityAt it’s essence, functional programming is functions, referential transparency and immutability ONLY
How many times have you been bitten by someone altering the contents of your collection?Can happen with closing over state very easily, or sending state to another method/function without considering whether or not it can be changed after it is sent.
Map is key to valueSet does not allow dups and doesn’t care about orderSequence allows dups and maintains orderList provides Lisp-like cons semantics, but is a linked list and can be slow, must prependVector is a bitmapped vector trie, organizing data into 32-element arrays. Very performant, holds 2.15 billion elements only seven levels deep
map, filter and flatMap in ScalaYou have the choice as to how to organize your code
Map is key to valueSet does not allow dups and doesn’t care about orderSequence allows dups and maintains orderList provides Lisp-like cons semantics, but is a linked list and can be slow, must prependVector is a bitmapped vector trie, organizing data into 32-element arrays. Very performant, holds 2.15 billion elements only seven levels deep
Functions are automatically curry-able in ML and Haskell, but has to be explicitly defined with multiple parameter lists in Scala
This is ALL you need to know. There is a ton of goodness in Akka that make performing actor-based work much simpler and reasonable than it has been in the past, as well as a codifying of best practices. Please check out the documentation if you are interested.
Don't use them until you understand them! And limit their scope when you do so nobody shoots their foot off.
Implicits will seem like voodoo at first. Exist in other languages, like C type coercion
Very powerful programming paradigmInverts imperative logic - apply your idempotent function to your dataThis is NOT monads, functors and the like, despite what you will hear in the communityAt it’s essence, functional programming is functions, referential transparency and immutability ONLY
Global type inferencing is found in ML, for example
Using Java's interfaces requires you to specify the inheritance structure in your code. What if you can't because you're using a library? What if you want to make the way your code handles situations orthogonal to it's inheritance structure
Using Java's interfaces requires you to specify the inheritance structure in your code. What if you can't because you're using a library? What if you want to make the way your code handles situations orthogonal to it's inheritance structure
This is the understandable reaction of most developers when they first engage the people who like CT. Or when they read their first blog post about how monads are like burritos or some other metaphor. I'm convinced what we need to do is understand that there is a whole vocabulary that must be learned in order for you to know what CT is.
Morphism is chewy brownie to a hard brownie
Would convert a brownie to a cookie, and a chewy brownie to a chewy cookie and hard brownie into hard cookie, but also chewy cookies into hard cookies just like the brownie because the morphism is preserved
They are not containers! They are not collections. Having a flatMap method does not mean that your type is monadic.Like a collection with flatMap. you won't know what they are by looking at code at first. Monads are ephemeral - they have to meet the laws of monads. Left and right identity as well as binding.
Is the language trying to support too many paradigms at the expense of usability? Should a language be responsible for providing convention as well as capability? I think not. You can start by using Scala as a DSL for Java and make your code more concise, more readable and more correct. As your abilities with the language grows, try expanding what you're doing, but keep in mind your limitations.
They are not containers! They are not collections. Having a flatMap method does not mean that your type is monadic.Like a collection with flatMap. you won't know what they are by looking at code at first. Monads are ephemeral - they have to meet the laws of monads. Left and right identity as well as binding.