My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
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.
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.
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!
Talk is about simple data structures like queue and Tree and their possible implementation in Scala. It also talks about binary search trees and their traversals.
"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
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.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
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 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.
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.
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.
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!
Talk is about simple data structures like queue and Tree and their possible implementation in Scala. It also talks about binary search trees and their traversals.
"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
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.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
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 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.
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
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.
Ten-page Brief Overview of Swift for Scala Developersihji
This is a ten-page brief overview document about Apple's brand new Swift programming language. This document is written in a Scala developer's view, so many advanced Swift features which do not have proper counterparts in Scala were baldly omitted. However, if you want to get a feeling that how Swift looks like, this is a perfect starter.
Getting Started with Apache Spark (Scala)Knoldus Inc.
In this session, we are going to cover Apache Spark, the architecture of Apache Spark, Data Lineage, Direct Acyclic Graph(DAG), and many more concepts. Apache Spark is a multi-language engine for executing data engineering, data science, and machine learning on single-node machines or clusters.
Secure practices with dot net services.pptxKnoldus Inc.
Securing .NET services is paramount for protecting applications and data. Employing encryption, strong authentication, and adherence to best coding practices ensures resilience against potential threats, enhancing overall cybersecurity posture.
Distributed Cache with dot microservicesKnoldus Inc.
A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm. Here we will look into implementation of Distributed Caching Strategy with Redis in Microservices Architecture focusing on cache synchronization, eviction policies, and cache consistency.
Introduction to gRPC Presentation (Java)Knoldus Inc.
gRPC, which stands for Remote Procedure Call, is an open-source framework developed by Google. It is designed for building efficient and scalable distributed systems. gRPC enables communication between client and server applications by defining a set of services and message types using Protocol Buffers (protobuf) as the interface definition language. gRPC provides a way for applications to call methods on a remote server as if they were local procedures, making it a powerful tool for building distributed and microservices-based architectures.
Using InfluxDB for real-time monitoring in JmeterKnoldus Inc.
Explore the integration of InfluxDB with JMeter for real-time performance monitoring. This session will cover setting up InfluxDB to capture JMeter metrics, configuring JMeter to send data to InfluxDB, and visualizing the results using Grafana. Learn how to leverage this powerful combination to gain real-time insights into your application's performance, enabling proactive issue detection and faster resolution.
Intoduction to KubeVela Presentation (DevOps)Knoldus Inc.
KubeVela is an open-source platform for modern application delivery and operation on Kubernetes. It is designed to simplify the deployment and management of applications in a Kubernetes environment. KubeVela is a modern software delivery platform that makes deploying and operating applications across today's hybrid, multi-cloud environments easier, faster and more reliable. KubeVela is infrastructure agnostic, programmable, yet most importantly, application-centric. It allows you to build powerful software, and deliver them anywhere!
Stakeholder Management (Project Management) PresentationKnoldus Inc.
A stakeholder is someone who has an interest in or who is affected by your project and its outcome. This may include both internal and external entities such as the members of the project team, project sponsors, executives, customers, suppliers, partners and the government. Stakeholder management is the process of managing the expectations and the requirements of these stakeholders.
Introduction To Kaniko (DevOps) PresentationKnoldus Inc.
Kaniko is an open-source tool developed by Google that enables building container images from a Dockerfile inside a Kubernetes cluster without requiring a Docker daemon. Kaniko executes each command in the Dockerfile in the user space using an executor image, which runs inside a container, such as a Kubernetes pod. This allows building container images in environments where the user doesn’t have root access, like a Kubernetes cluster.
Efficient Test Environments with Infrastructure as Code (IaC)Knoldus Inc.
In the rapidly evolving landscape of software development, the need for efficient and scalable test environments has become more critical than ever. This session, "Streamlining Development: Unlocking Efficiency through Infrastructure as Code (IaC) in Test Environments," is designed to provide an in-depth exploration of how leveraging IaC can revolutionize your testing processes and enhance overall development productivity.
Exploring Terramate DevOps (Presentation)Knoldus Inc.
Terramate is a code generator and orchestrator for Terraform that enhances Terraform's capabilities by adding features such as code generation, stacks, orchestration, change detection, globals, and more . It's primarily designed to help manage Terraform code at scale more efficiently . Terramate is particularly useful for managing multiple Terraform stacks, providing support for change detection and code generation 2. It allows you to create relationships between stacks to improve your understanding and control over your infrastructure . One of the key features of Terramate is its ability to detect changes at both the stack and module level. This capability allows you to identify which stacks and resources have been altered and selectively determine where you should execute commands.
Clean Code in Test Automation Differentiating Between the Good and the BadKnoldus Inc.
This session focuses on the principles of writing clean, maintainable, and efficient code in the context of test automation. The session will highlight the characteristics that distinguish good test automation code from bad, ultimately leading to more reliable and scalable testing frameworks.
Integrating AI Capabilities in Test AutomationKnoldus Inc.
Explore the integration of artificial intelligence in test automation. Understand how AI can enhance test planning, execution, and analysis, leading to more efficient and reliable testing processes. Explore the cutting-edge integration of Artificial Intelligence (AI) capabilities in Test Automation, a transformative approach shaping the future of software testing. This session will delve into practical applications, benefits, and considerations associated with infusing AI into test automation workflows.
State Management with NGXS in Angular.pptxKnoldus Inc.
NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations. In this session we will go through the main for components of NGXS -Store, Actions, State, and Select.
Authentication in Svelte using cookies.pptxKnoldus Inc.
Svelte streamlines authentication with cookies, offering a secure and seamless user experience. Effortlessly manage sessions by storing tokens in cookies, ensuring persistent logins. With Svelte's simplicity, implement robust authentication mechanisms, enhancing user security and interaction.
OAuth2 Implementation Presentation (Java)Knoldus Inc.
The OAuth 2.0 authorization framework is a protocol that allows a user to grant a third-party web site or application access to the user's protected resources, without necessarily revealing their long-term credentials or even their identity. It is commonly used in scenarios such as user authentication in web and mobile applications and enables a more secure and user-friendly authorization process.
Supply chain security with Kubeclarity.pptxKnoldus Inc.
Kube clarity is a comprehensive solution designed to enhance supply chain security within Kubernetes environments. Kube clarity enables organizations to identify and mitigate potential security threats throughout the software development and deployment process.
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
In this session, we will delve into the world of web scraping with JSoup, an open-source Java library. Here we are going to learn how to parse HTML effectively, extract meaningful data, and navigate the Document Object Model (DOM) for powerful web scraping capabilities.
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
Dive into the fundamental aspects of Akka gRPC and learn to leverage its power in building compact and efficient distributed systems. This session aims to equip attendees with the essential skills and knowledge to leverage Akka and gRPC effectively in building robust, scalable, and distributed applications.
Entity Core with Core Microservices.pptxKnoldus Inc.
How Developers can use Entity framework(ORM) which provides a structured and consistent way for microservices to interact with their respective database, prompting independence, scaliblity and maintainiblity in a distributed system, and also provide a high-level abstraction for data access.
Introduction to Redis and its features.pptxKnoldus Inc.
Join us for an interactive session where we'll cover the fundamentals of Redis, practical use cases, and best practices for incorporating Redis into your projects. Whether you're a developer, architect, or system administrator, this session will equip you with the knowledge to harness the full potential of Redis for your applications. Get ready to elevate your understanding of in-memory data storage and revolutionize the way you handle data in your projects with Redis
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
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.
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.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
3. SBT
Build tool for Scala based projects
Scala based frameworks like Akka uses it
SBT build definition uses scala based DSL
Incremental compilation
Works with mixed Scala and Java based projects
4. SBT: Lets create a project
SBT Installation download jar and create a script
Instructions: xsbt wiki
Descend in directory where you wanna create the project
In terminal type sbt
Once the sbt is started enter following commands
set name := “ScalaKnolx”
set version := “1.0”
set scalaVersion := “2.9.1”
session save
exit
Open build.sbt and have a look!!
5. SBT: Eclipse IDE
Add Typesafe repo and sbteclipse plugin
In build.sbt
resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"
libraryDependencies += "org.scalatest" %% "scalatest" % "1.6.1"
libraryDependencies += "junit" % "junit" % "4.9"
Create project/plugins.sbt and add sbteclipse plugin
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.0.0")
Execute sbt eclipse
It will generate eclipse related configs and now we are ready to import
this project in eclipse!!
6. Scala Introduction
Scala is a JVM based language
Scala combines FP and OO which makes it a scalable language
Scala has a REPL
Scala is interoperable with Java
7. Scala is a scripting language
It has a REPL.
Types can be inferred
Less Boilerplate
Scala> var capital = Map(“US” → “Washington”, “France” → “Paris”)
Capital: Map[String, String] = Map(US-> Washington, France->Paris)
Scala> capital += (“japan” → “Tokyo”)
Scala> capital(“France”)
Res2: String = Paris
8. Scala is OO
Every value is an object
Every operation is method call
Exceptions to this in java like statics and primitives are removed
Scala> (1).hashCode
Res1: Int = 1
Scala> (1).+(2)
Res2: Int = 3
9. Scala compared to Java
Scala adds Scala removes
+ pure object system - static members
+ operator overloading - primitive types
+ closures - break, continue
+ mixin composition with traits - special treatment of interfaces
+ existential types - wildcards
+ abstract types - raw types
+ pattern matching - enums
10. Scala cheat sheet (1): Definitions
Scala method definitions Java method definitions
def fun(x: Int) = { Int fun(int x) {
result return result
} }
def fun = result (no parameterless methods)
Scala variable definitions Java variable definitions
var x: Int = expression Int x = expression
val x: String = expression final String x = expression
11. Scala cheat sheet (2): Definitions
Scala Class and Object Java method definitions
class Sample(x: Int, p: Int) { class Sample {
def instMeth(y: Int): Int = x + y private final int x;
} public final int p;
object Sample { Sample(int x, int p) {
def staticMeth(x: Int, y: Int): Int = x * y this.x = x;
} this.p = p;
}
int instMeth(int y) {
return x + y;
}
static int staticMeth(int x, int y) {
return x * y;
}
}
12. Scala cheat sheet (3): Traits
Scala Trait Java Interface
trait T { Interface T {
var field = “!” Int abstractMth(String x)
}
def abstractMth(x: Int): Int
(no concrete methods)
def concMth(x: String) = x + field (no fields)
}
Scala mixin composition Java extension plus implementation
class C extends Super with T class C extends Super implements T
13. Scala HOF
Scala is also FP along-with OO
This means that Function is also an Object
They can be passed along as objects
private def higherOrderFunction(f: Int => Int, x:
Int): Int = {
f(x) + 1
}
14. Scala Pattern Match
All that is required is to add case keyword to each class that is to
be pattern matchable
Similar to switch except that Scala compares objects as
expressions
getInteger(4) match {
case 4 => println("four")
case _ => println("not four")
}
def getInteger(x: Int): Int = {
x
}
15. Scala Traits
They are fundamental unit of code reuse in Scala
They encapsulates method and field definitions, which can be
reused by mixing them in classes
Unlike class inheritance a class can mix any number of traits
Unlike Interfaces they can have concrete methods
16. Scala Collections
Class Person(val name: String, age: Int)
val people: Array[Person]
val(minors, adults) = people partition (_.age < 18)
Three concepts:
- pattern mach
- infix method call
- a function value
17. Scala way of Collections
De-emphasize destructive updates
Focus on transformers that map collections to collections
Have complete range of persistent collections
18. Collection Properties
Object-Oriented
Generic: List[T], Map[K, V]
Optionally persistent: scala.collections.immutable
Higher order: methods like foreach, map, filter
Uniform return type principle: operations return same
type as their left operand
20. Using Collections: Map and Filter
scala> val xs = List(1,2,3)
xs: List[Int] = List(1,2,3)
scala> val ys = xs map (x => x + 1)
xs: List[Int] = List(2,3,4)
scala> val ys = xs map(_ + 1)
ys: List[Int] = List(2,3,4)
scala> val zs = ys filter (_ % 2 == 0)
zs: List[Int] = List(2,4)
scala> val as = ys map (0 to _)
as: List[scala.collection.immutable.Range.Inclusive] =
List(Range(0,1), Range(0,1,2), Range(0,1,2,3))
21. Using Collections: flatMap and groupBy
scala> val bs = as.flatten
bs: List[Int] = List(0,1,0,1,2,0,1,2,3)
scala> val bs = ys flatMap(0 to _)
bs: List[Int] = List(0,1,0,1,2,0,1,2,3)
scala> val fruit = Vector(“apples”, “oranges”, “ananas”)
fruit: scala.collection.immutable.Vector[java.lang.String] =
Vector(“apples”, “oranges”, “ananas”)
scala> fruit groupBy (_.head)
res2: scala.collection.immutable.Map[char,
scala.collection.immutable.Vector[java.lang.String]] = Map(a->
Vector(apples, ananas), o -> Vector(oranges))
22. Using Collections: for notation
scala> for(x ← xs) yield x + 1 // map
res0: Seq[Int] = List(2,3,4)
scala> for(x ← res0 if x % 2 == 0) yield x // filter
res1: Seq[Int] = List(2,4)
scala> for(x ← xs; y ← 0 to x) yield y // flatMap
res2: Seq[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)
23. String also a collection
Even String is a collection that means that we can apply higher
order functions on it
scala> val aString = “hello world”
aString: java.lang.String = hello world
scala> aString map (_.toUpper)
res1: String = HELLO WORLD
25. Scala Collection Hierarchy
All collection classes are in scala.collection or one of its sub-
packages mutable, immutable and generic
Root collections are in scala.collection define same interface as
immutable collections and mutable collections add some
modification operations to make it mutable
The generic package contains building block for implementing
collections
29. Commonality In Collections
All classes are quite common. For instance every collection can be
created by same uniform syntax
Set(1, 2, 3)
Seq(1, 2, 3)
Traversable(1, 2, 3)
Map(“x” → 24, “y” → 25)
Applies with specific collection implementations
List(1, 2, 3)
HashMap(“x” → 24, “y” → 25)
All these collections get displayed with toString in same way
30. Trait Traversable
Top of Collection Hierarchy. Its abstract method is foreach:
def foreach[U](f: Elem => U)
Traversable also provides lot of concrete methods they fall in following
categories
31. Everything is a library
Collections feel that they are language constructs
Language does not contain any collection related constructs
- no collection types
- no collection literals
- no collection operators
Everything is in library
They are extensible
32. Scala Test
Scala Test is an open source framework for Java platform
With ScalaTest we can test either Scala or Java code
Integrates with popular tools like jUnit, TestNG, Ant, Maven and SBT
Designed to do different styles of testing like Behavior Driven Design for
example
33. Scala Test Concepts
Three concepts:
Suite: A collection of tests. A test is anything which has a name and can
succeed or fail
Runner: ScalaTest provides a runner application and can run a suite of
tests
Reporter: As the tests are run, events are fired to reporter, it takes care of
presenting results back to user
35. Scala Test: under the hood
When you run a Test in Scala Test you basically invoke
run(Option[String], Reporter, …) on Suite object
It then calls runNestedSuites(Reporter, …)
And it calls runTests(Option[String], Reporter, …)
runNestedSuites(Reporter, …):
Invokes nestedSuites(): List[Suite] to get a list of nested suites
runTests(Option[String], Reporter, …) will call def testNames:
Set[String] to get set of test names to run. For each test it calls
runTest(Reporter, …) It wraps the test code as a Function object with a
name and passes it to the withFixture(NoArgTest) which actually runs the
test
38. Scala Test: Available Traits
Suite
FunSuite
Spec
FlatSpec
WordSpec
FeatureSpec
Assertions
ShouldMatchers
MustMatchers
39. Suite
Traits approach to writing tests. Create classes extending Suite
and define test methods
Test methods have names testXXXX. All methods must be public
Scala Test provides === operator. It is defined in Trait Assertions.
Allows the failure report to include both right and left values
40. FunSuite
For writing Functional Tests use FunSuite Fun => functional
“test” is a method defined in FunSuite Trait. Test name goes in
parentheses and test body goes in curly braces
The test code in curly braces is passed as a by-name parameter to
“test” method which registers for later execution
41. Assignment
Lets map the world. We have Continents and Countries
Make a Collection hierarchy to hold the above information
Write method on the collection hierarchy to get countries of a
continent
Write method on the collection hierarchy to get continent for a
country
Write tests using FunSuite to test the methods created above