SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
Introducing Scala


       Meetu Maltiar
    Principal Consultant
          Knoldus
Agenda

Starting a Scala project
Scala as a language
Scala Collections
Scala Test
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
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!!
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!!
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
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
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
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
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
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;
                                                    }
                                                }
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
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
 }
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
 }
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
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
Scala way of Collections


De-emphasize destructive updates

Focus on transformers that map collections to collections

Have complete range of persistent collections
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
Uniform Return Type Principle
scala> val ys = List(1,2,3)
ys: List[Int] = List(1,2,3)

scala> val xs: Seq[Int] = ys
xs: Seq[Int] = List(1,2,3)

scala> xs map(_ + 1)
res0: Seq[Int] = List(2,3,4)

scala> ys map(_ + 1)
res1: List[Int] = List(2,3,4)
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))
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))
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)
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
Using Maps
scala> val m = Map(1 → “ABC”, 2 → “DEF”, 3 → “GHI”)
m: scala.collection.immutable.Map[Int, java.lang.String] = Map(1 →
ABC, 2 → DEF, 3 → GHI)

scala> m(2)
res1: java.lang.String = DEF

scala> m + (4 → “JKL”)
res2: scala.collection.immutable.Map[Int, java.lang.String] = Map(1
→ ABC, 2 → DEF, 3 → GHI, 4 → JKL)

scala> m map {case (k, v) => (v, k)}
res2: scala.collection.immutable.Map[java.lang.String, Int] =
Map(ABC → 1, DEF → 2, GHI → 3)
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
Scala.Collection Hierarchy
Scala.Collection.Immutable
Overview of Collections
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
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
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
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
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
Scala Test Is Customizable
                  Suite
                 <<trait>>

 def expectedTestCount(Filter: Int)
 def testNames: Set[String]
 def tags: Map[String, Set[String]]
 def nestedSuites: List[Suite]
 def run(Option[String], Reporter, …)
 def runNestedSuites(Reporter, …)
 def runTests(Option[String]), Reporter
 def runTest(Reporter, …)
 def withFixture(NoArgTest)
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
Pick a core Trait
Mixin other Traits
Scala Test: Available Traits
Suite
FunSuite
Spec
FlatSpec
WordSpec
FeatureSpec
Assertions
ShouldMatchers
MustMatchers
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
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
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

Weitere ähnliche Inhalte

Was ist angesagt?

Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Jonas Bonér
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with ScalaDenis
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In ScalaKnoldus Inc.
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: NotesRoberto Casadei
 

Was ist angesagt? (18)

Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Scala collection
Scala collectionScala collection
Scala collection
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Suit case class
Suit case classSuit case class
Suit case class
 
Data Structures In Scala
Data Structures In ScalaData Structures In Scala
Data Structures In Scala
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Joy of scala
Joy of scalaJoy of scala
Joy of scala
 
Scala collections
Scala collectionsScala collections
Scala collections
 
Real generics
Real genericsReal generics
Real generics
 
Google06
Google06Google06
Google06
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
C# programming
C# programming C# programming
C# programming
 

Ähnlich wie Scala Bootcamp 1

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectivegabalese
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaBrian Hsu
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and HaskellHermann Hueck
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scalaMichel Perez
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Jesper Kamstrup Linnet
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash courseHolden Karau
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developersihji
 

Ähnlich wie Scala Bootcamp 1 (20)

Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Meet scala
Meet scalaMeet scala
Meet scala
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspectiveScala or functional programming from a python developer's perspective
Scala or functional programming from a python developer's perspective
 
Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
Introduction to scala
Introduction to scalaIntroduction to scala
Introduction to scala
 
Scala
ScalaScala
Scala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Practical cats
Practical catsPractical cats
Practical cats
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
2014 holden - databricks umd scala crash course
2014   holden - databricks umd scala crash course2014   holden - databricks umd scala crash course
2014 holden - databricks umd scala crash course
 
Ten-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala DevelopersTen-page Brief Overview of Swift for Scala Developers
Ten-page Brief Overview of Swift for Scala Developers
 

Mehr von Knoldus Inc.

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 

Mehr von Knoldus Inc. (20)

Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 

Kürzlich hochgeladen

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Scala Bootcamp 1

  • 1. Introducing Scala Meetu Maltiar Principal Consultant Knoldus
  • 2. Agenda Starting a Scala project Scala as a language Scala Collections Scala Test
  • 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
  • 19. Uniform Return Type Principle scala> val ys = List(1,2,3) ys: List[Int] = List(1,2,3) scala> val xs: Seq[Int] = ys xs: Seq[Int] = List(1,2,3) scala> xs map(_ + 1) res0: Seq[Int] = List(2,3,4) scala> ys map(_ + 1) res1: List[Int] = List(2,3,4)
  • 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
  • 24. Using Maps scala> val m = Map(1 → “ABC”, 2 → “DEF”, 3 → “GHI”) m: scala.collection.immutable.Map[Int, java.lang.String] = Map(1 → ABC, 2 → DEF, 3 → GHI) scala> m(2) res1: java.lang.String = DEF scala> m + (4 → “JKL”) res2: scala.collection.immutable.Map[Int, java.lang.String] = Map(1 → ABC, 2 → DEF, 3 → GHI, 4 → JKL) scala> m map {case (k, v) => (v, k)} res2: scala.collection.immutable.Map[java.lang.String, Int] = Map(ABC → 1, DEF → 2, GHI → 3)
  • 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
  • 34. Scala Test Is Customizable Suite <<trait>> def expectedTestCount(Filter: Int) def testNames: Set[String] def tags: Map[String, Set[String]] def nestedSuites: List[Suite] def run(Option[String], Reporter, …) def runNestedSuites(Reporter, …) def runTests(Option[String]), Reporter def runTest(Reporter, …) def withFixture(NoArgTest)
  • 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
  • 36. Pick a core Trait
  • 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