SlideShare a Scribd company logo
Knoldus
Kick Start Scala Traits
Knoldus
Programming In Scala
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching

Recommended for you

Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory

Category theory concepts such as objects, arrows, and composition directly map to concepts in Scala. Objects represent types, arrows represent functions between types, and composition represents function composition. Scala examples demonstrate how category theory diagrams commute, with projection functions mapping to tuple accessors. Thinking in terms of interfaces and duality enriches both category theory and programming language concepts. Learning category theory provides a uniform way to reason about programming language structures and properties of data types.

scala
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet

This document provides a dictionary of scala programming concepts including definitions of common jargon like ADT, typeclasses, extension methods, and call-by semantics. It defines ADT as algebraic data types, which were introduced in languages like Algol 60 and ML, and pattern matching which allows decomposing ADT values. Typeclasses are defined as rules for types like equality, with instances providing implementations. Extension methods and implicit conversions add methods to types via implicit parameters. Call-by-name and call-by-need semantics are discussed in relation to lazy evaluation.

scala
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala

The Scala programming language, its history, design choices, syntax basics, functional concepts, monads

scalamonadfunctional programming
Knoldus
In 2003, Martin Odersky and his team set
out to create a “scalable” language that
fused important concepts from functional
and object-oriented programming. The
language aimed to be highly interoperable
with Java, have a rich type system, and to
allow developers to express powerful
concepts concisely.
Knoldus
Knoldus
Knoldus
Functional programming
contructs make it easy
to build interesting
things quickly from small
parts
Object oriented constructs
make it easy to structure
large systems and
adapt to new demands

Recommended for you

Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet

This document provides a cheat sheet overview of Scala concepts including packages, imports, variables, constants, classes, traits, generics, methods, functions, operators, arrays, main methods, annotations, assignments, selection, iteration and references. Key points are that Scala uses packages similarly to Java but with curly brace delimiters, imports can be used anywhere in a file, variables use 'var', constants use 'val', classes inherit from Any and can use traits for mixins, generics are defined with type parameters, functions are objects, operators are methods, arrays are classes, main returns Unit, and assignments use = while iteration prefers recursion over loops.

arduino aficionado
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala

This presentation was presented by Meetu Maltiar and Vikas Hazrati @OssCamp on 6th Sep 2009 at Netaji Subash Institute of Technology.

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

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

underscorescalatype classes
Knoldus
Object oriented
Everything is an object, pure OO
Not like java where we have primitives / static
fields and methods which are not members of any
object
1+2 is actually 1.+(2)
1 + 2
//> res1: Int(3) = 3
1 .+(2)
//> res2: Int(3) = 3
Knoldus
Functional language
Functions are first class values
Encourages immutability where operations map
input values to output rather than change data in
place
Knoldus
Concise Code
Knoldus
Expressive
val numbers = 1 to 10
//>Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers filter { _ % 2 == 0 }
//> Vector(2, 4, 6, 8, 10)

Recommended for you

All about scala
All about scalaAll about scala
All about scala

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

scala
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API

This document summarizes a talk given about Nokia's migration to Scala for its Places API. The key points are: 1) Nokia migrated its Places API codebase to Scala to take advantage of Scala's features like its powerful type system, immutable data structures, and functional programming capabilities. 2) The migration was done gradually over time while continuing to develop new features. They discovered many benefits of Scala along the way like improved test readability and JSON parsing capabilities. 3) Nokia uses Scala features like case classes, options, and functions to model data and add type safety to its codebase. This uncovered bugs that would have been hard to find in Java.

nokiaapiscala
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes

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.

scalaprogrammingfunctional programming
Knoldus
High Level
Finding an upper case character
Knoldus
Statically Typed
Verifiable Properties
Safe Refactorings
Documentation
Cannot add boolean to List[Int]
Strong type inference
val x = Map(1->”somevalue”)
Knoldus
1. Create a new worksheet called Lab1
2. Print “Hello Scala World”
3. See the program execute in Worksheet
Knoldus
1 + 2
What do you see?
/> res1: Int(3) = 3

Recommended for you

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

This document summarizes some of the key differences between Scala and Java syntax. It covers topics like type definitions, variables, methods, classes, traits, collections, exceptions, control flow, and packages. Overall, the document shows that Scala code is more concise and expressive than equivalent Java code for many common programming constructs.

Introducing scala
Introducing scalaIntroducing scala
Introducing scala

This presentation was presented as knowledge session at Knoldus. It is meant for Java professionals to quick-start them in Scala.

scalatestsbtscala
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008

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

scala
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Variables
val
var
Similar to final
Mutable
Knoldus
Why does this code compile?
Type Inference
val msg:String = "Hello World!" //> msg : String = Hello World!
Knoldus
Sometimes variables need to mutate
var description = "start" > description : java.lang.String = start
description = "end"

Recommended for you

Scala Intro
Scala IntroScala Intro
Scala Intro

Scala Intro training @ Lohika, Odessa, UA. This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.

introtrainingbasics
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java

Session presented at the 6th IndicThreads.com Conference on Java held in Pune, India on 2-3 Dec. 2011. http://Java.IndicThreads.com

Scala Intro
Scala IntroScala Intro
Scala Intro

This document summarizes key features of the Scala programming language. Some key points include: - Scala runs on the Java Virtual Machine (JVM) and allows for type inference, immutable values, functional programming patterns like pattern matching, and object-oriented features like traits for inheritance. - Scala favors immutable values over mutable variables for scalability. Features like actors allow for concurrency without shared mutable state. - Scala code can be compiled to JavaScript using Scala.js, allowing full-stack development in a single language. - Traits provide a powerful way to do multiple inheritance by combining traits and classes at runtime.

scala meetup torino agilelab
Knoldus
Method Definition
Knoldus
Unit
A result of Unit indicates that the function returns no interesting
value
def justGreet(name:String) = println("Hello " + name) //>
justGreet: (name: String)Unit
Similar to void in Java
Knoldus
Everything returns a value
val number = {
val x: Int = 7
val y: Int = 9
x + y
} //> number : Int = 16
if (1 < 10) 15 else 17
Knoldus
Everything returns a value
val number = {
val x: Int = 7
val y: Int = 9
x + y
} //> number : Int = 16
if (1 < 10) 15 else 17

Recommended for you

Scala for curious
Scala for curiousScala for curious
Scala for curious

This document provides an introduction to the Scala programming language. It discusses what Scala is, how to get started, basic concepts like mutability and functions, and Scala features like classes, traits, pattern matching, and collections. Scala combines object-oriented and functional programming. It runs on the Java Virtual Machine and is compatible with Java. The document provides code examples to demonstrate Scala concepts and features.

Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala

This document discusses various techniques for working with types in Scala, including: 1. The main alternatives for Scala types including classical OO, algebraic, generic, and structured types. It recommends choosing styles based on use cases and setting guidelines. 2. The differences between run-time and compile-time dispatch and how they are implemented in Scala. 3. Techniques for working with types including tagged types, type aliases, and implicit evidence to provide different behaviors based on types known at compile-time. 4. Resources for learning more about advanced type-level programming in Scala, particularly the Shapeless library.

shapelessscalatypelevel
Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way

This document discusses using Akka and actors for building scalable and concurrent applications in Scala. It introduces actors as fundamental units of computation that communicate asynchronously via message passing. Akka provides tools for creating actor systems and hierarchies. The document uses a monitoring application called Scotchdog as an example, with actors to represent services that are monitored by a watchdog actor. It describes how messages are used to start, stop and check services, and how the watchdog can aggregate status from child actors. The document also briefly mentions using Akka's scheduler and finite state machines to implement more complex actor behaviors.

Knoldus
Functions, first look
List(1,2,3).foreach(l=>println(l))
List(1,2,3).foreach(l=>println(l))
List(1,2,3).foreach(println(_))
List(1,2,3) foreach (println(_))
List(1,2,3) foreach (println)
List(1,2,3) foreach println
Foreach takes a function of
what needs to be done
List(1,2,3) foreach ((x:Int)=>println(2*x))
Knoldus
Function Literal
What we pass inside of foreach is a function literal
List(1,2,3) foreach ((x:Int)=>println(2*x))
Knoldus
Working with Arrays
val greetStrings = new Array[String](3) //> greetStrings :
Array[String] = Array(null, null, null)
greetStrings(0) = "Bank"
greetStrings(1) = "of"
greetStrings(2) = "America"
greetStrings(0) = "BANK"
Notice?
val greetStrings = List(1,2,3)
greetStrings(0) = "Bank"
greetStrings(1) = "of"
greetStrings(2) = "America"
greetStrings(0) = "BANK"
Knoldus
No Operators

Recommended for you

Akka -- Scalability in Scala and Java
Akka -- Scalability in Scala and JavaAkka -- Scalability in Scala and Java
Akka -- Scalability in Scala and Java

Akka, an actor framework written in Scala (that also supports Java) provides you with all the benefits commonly found in actor frameworks, but without the kinks. This presentation will explore actor based concurrency using Akka, and dwell on some of Akka's stregths, culminating in the equation "Transactional Memory + Actors = Transactors".

akkajavascala
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter

A presentation at Twitter's official developer conference, Chirp, about why we use the Scala programming language and how we build services in it. Provides a tour of a number of libraries and tools, both developed at Twitter and otherwise.

configgyspecsostrich
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013

A comparison on JVM Web Frameworks. Includes strategies for choosing and results from research by InfoQ and devrates.com. Also, lots of pretty graphs. See blog post about this presentation at http://raibledesigns.com/rd/entry/devoxx_france_a_great_conference and video recording at http://raibledesigns.com/rd/entry/video_of_comparing_jvm_web

jvmwebframeworkscomparison
Knoldus
Lists
cons
concatenation
Knoldus
No Operators
Knoldus
Lists
cons
concatenation
Knoldus
Tuples
Immutable like lists, but can have different types of elements
Why we cannot get values out of a Tuple just like list?

Recommended for you

Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala

This document discusses asynchronous I/O in Java and Scala using the Play Framework. It describes how LinkedIn uses a service-oriented architecture with hundreds of services making requests to each other. It then covers how Play supports non-blocking I/O using asynchronous code, promises, and futures to allow parallel requests without blocking threads. Key points covered include using map and flatMap to transform promises and futures, handling errors and timeouts, and the benefits of non-blocking I/O for scalability.

play frameworkjavalinkedin
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka

Slides for my talk event-sourced architectures with Akka. Discusses Akka Persistence as mechanism to do event-sourcing. Presented at Javaone 2014 and Jfokus 2015.

akkaakka persistencejava
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka

Akka is using the Actors together with STM to create a unified runtime and programming model for scaling both UP (multi-core) and OUT (grid/cloud). Akka provides location transparency by abstracting away both these tangents of scalability by turning them into an ops task. This gives the Akka runtime freedom to do adaptive automatic load-balancing, cluster rebalancing, replication & partitioning

actorsconcurrencyakka
Knoldus
Sets and Maps
By default, we are provided with the immutable collections
Knoldus
What is happening here
var treasureMap = Map(1->"a", 2->"b")
treasureMap += (3->"c")
What happens if we change treasureMap to val?
Why?
Knoldus
Understanding Functional Style
No vars
No methods with side effects – Unit
No while loops
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching

Recommended for you

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu

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

Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns

Most developers are aware about design patterns. The difficulty is not in understanding them but in getting an intuitive understanding of when and how to apply them. In this session, we'll go through a case study of how a tiny interpreter (of course written in Java) may implement different design patterns. The link to source code is: https://github.com/CodeOpsTech/InterpreterDesignPatterns

interpreterdesign principlescompiler
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks

Oleksii Petinov during his presentation gave the audience the overview of his vision of Scala pros and contras. In his vision Scala smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive. There is admittedly some truth to the statement that “Scala is complex”, but the learning curve is well worth the investment.

javaitbraindev
Knoldus
Singleton objects
● A singleton object is like a class and its sole
instance
● Use the keyword object to define a singleton
object:
object Foo {
val bar = "Bar"
}
Access singleton objects like Foo.bar
Knoldus
OO Features
Knoldus
Classes
● Classes are blueprints for objects
● class Bank – is a valid class definition
No Semicolon
No access modifier, public by default
No curly braces since no body
Create a new instance
new Bank
Knoldus
class Bank(id:Int, name:String)
new Bank(1,"BoA")
//> res5: lab1.Bank =
lab1$anonfun$main$1$Bank$1@1372a7a
Parameters are val and cannot be accessed
from outside

Recommended for you

Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos

A presentation from Iulian Dragos of Typesafe that gives an overview of the Scala programming language. The presentation was given at a Functional Angle conference in Timisoara, Romania sponsored by 3Pillar. Iulian Dragos has been working on Scala since 2004. He currently works for Typesafe, a start-up that was co-founded by Scala’s creator, Martin Odersky.

software developmentsoftware product developmentapplication development
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers

Scala is a programming language that blends object-oriented and functional programming styles. It is designed to interoperate with Java code and runs on the Java Virtual Machine. Some key features of Scala include case classes, pattern matching, traits for mixing functionality, and immutable data structures. Scala code compiles to Java bytecode, allowing seamless use of Java libraries and tools.

scala
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers

Scala is a programming language that blends object-oriented and functional programming styles. It is designed to interoperate with Java code and runs on the Java Virtual Machine. Some key features of Scala include case classes, pattern matching, traits for mixing behavior, and immutable data structures. Scala code compiles to Java bytecode, allowing seamless use of Java libraries and tools.

miles sabinjavascala
Knoldus
class Bank(id:Int, name:String)
val b = new Bank(1,"BoA")
b.id
Knoldus
class Bank(id:Int, name:String)
val b = new Bank(1,"BoA")
b.id
Knoldus
Add another parameter to bank
Create another instance of bank
Knoldus
Auxilliary Constructors
class Bank(id: Int, name: String) {
def this(str: String) = this(1, str)
def this() = this(1, "")
}
Must immediately call another constructor
with this

Recommended for you

Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans

JavaFX is a software platform for creating rich internet applications (RIAs) using Java that can compete with Flash/Flex and Silverlight, it is based on Java and the JavaFX runtime and includes tools like JavaFX Script for building the user interface and NetBeans as an integrated development environment. JavaFX aims to simplify building RIAs with features like bindings, listeners and components while allowing access to the full Java runtime.

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

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

oopoop 2010scala
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals

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

scalatutorialfunctional programming
Knoldus
Accessing fields of a class
class Bank(id: Int, name: String) {
val kind = "Blue"
var address = "Delhi"
def this(str: String) = this(1, str)
def this() = this(1, "")
}
val b = new Bank(1, "BoA")
b.address = "Mumbai"
b.kind = "op"
immutable
mutable
Knoldus
Making fields from class parameters
class Bank(val id: Int, var name: String) {
val kind = "Blue"
var address = "Delhi"
def this(str: String) = this(1, str)
def this() = this(1, "")
}
See if you can access id and name outside the class now
Knoldus
Make a Bank class with the following immutable
parameters
Id, name, address, city
Create a bank instance and access its fields
Make a Account class with the following immutable
parameters
Id, name, amount
Create a Account instance and access its fields
Knoldus
Define a debit method in the Account class
def debit(amount:Int):Int = {...}

Recommended for you

Scala on Android
Scala on AndroidScala on Android
Scala on Android

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

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

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

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

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

spascala
Knoldus
class Account(id: Int, name: String, amount: Int) {
def debit(debitAmount: Int): Int = amount - debitAmount
def -(debitAmount: Int): Int = amount - debitAmount
}
new Account(1, "VikasAccount", 100) - 20 //
Knoldus
Default Parameters
class Account(id: Int, name: String, amount: Int = 0) {
def debit(debitAmount: Int): Int = amount - debitAmount
def -(debitAmount: Int): Int = amount - debitAmount
}
With default parameters,
new Account(1,"Another")
Knoldus
Singleton objects
● A singleton object is like a class and its sole
instance
● Use the keyword object to define a singleton
object:
object Foo {
val bar = "Bar"
}
Access singleton objects like Foo.bar
Knoldus
Singleton Objects
● Can be thought to be like static in Java but
these are real objects which can inherit and be
passed around

Recommended for you

JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop

Put on by USC's Upsilon Pi Epsilon as part of Wonderful World of Web2.0 Workshop Series. http://pollux.usc.edu/~upe/

Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala

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

programmingscalafunctional programming
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training

This document provides an overview of JavaScript training topics including: - Client-side programming fundamentals - JavaScript syntax like variables, types, and arrays - Object-oriented programming concepts like classes and methods - Interacting with HTML and CSS - Using development tools like Netbeans and Eclipse - Advanced topics like scope, closures, prototypes, and JSON

trainingjavascript
Knoldus
Companion Objects
● If a singleton object and a class or trait share
the same name, package and file, they are
called companions
class Bank(val id: Int, var name: String) {
private val kind = "Blue"
var address = "Delhi" + Bank.city
def this(str: String) = this(1, str)
def this() = this(1, "")
}
object Bank {
private val city = "Delhi"
val newBank = new Bank(1,"ABC")
newBank.kind
}
Class or trait can
access private
member of
Companion
object
Knoldus
Create a companion object for Account
Create a method in account object to get the type
of account like Saving or Checking
Or
Any other method that you like
Knoldus
Understanding Predef
Predef object provides definitions which are accessible in all
Scala compilation units without explicit qualification
Aliases for types such as Map, Set and List
Assertions – Require and Ensuring
Console IO – such as print, println, readLine, readInt. These
methods are otherwise provided by scala.Console
Knoldus
Add a require assertion to the account that id has
to be > 0
Add any other preconditions for accounts

Recommended for you

(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 offers benefits from adopting it such as increased productivity through concise and expressive code, static typing with type inference, support for both object-oriented and functional programming paradigms, and interoperability with Java. Switching from Java to Scala involves some changes like using val for immutable variables and var for mutable, but overall the syntax is quite similar which eases the transition.

highlightslanguagefeatures
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala

This presentation introduces the main features of Scala, an object oriented and functional programming language. The main focus of the slides is to show how the language implements natively some of the patterns and best practices that are no present in other programming languages, such as Java, C++ and so on. In detail, the presentation spans these concepts: - Language's main syntax - Classes, abstract classes, objects and traits (mixin) - The Option class - An introduction to generics - Implicit classes - Functions - Recursion (simple and tail) - Currying - Call by value / name The presentation is took from the Software Engineering course I run in the bachelor-level informatics curriculum at the University of Padova.

software engineeringsoftware developmentobject oriented programming
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala

The document provides an introduction and overview of Scala concepts. In 3 sentences: Scala is an object-oriented and functional language that runs on the Java Virtual Machine. It combines object-oriented and functional programming which allows for modularity, extensibility, and composition. The document discusses Scala concepts like expressions, types, values, classes, traits, objects, pattern matching and more to build a fundamental understanding of how Scala programs work.

scalaprogrammingsoftware development
Knoldus
class Bank(val id: Int, var name: String) {
require(id > 0)
private val kind = "Blue"
var address = "Delhi"
Bank.city
def this(str: String) = this(1, str)
def this() = this(1, "")
}
object Bank {
val city = "Delhi"
val newBank = new Bank(1, "ABC")
}
new Bank(0,"ll") //>
java.lang.IllegalArgumentException: requirement failed
Knoldus
Case Classes
Add syntactic convenience to your class
Add factory method with
Name of class so we don't
Need to do new
All parameters in the
Parameter list get a val by
default
Natural implementation of
toString, hashCode and
equals to the class
Support pattern matching
Small price
In terms of
Size
Knoldus
case class Bird(name: String)
val b = Bird("pigeon") //> b : lab1.Bird = Bird(pigeon)
val c = Bird("pigeon") //> c : lab1.Bird = Bird(pigeon)
b == c //> res7: Boolean = true
Knoldus
Try converting the Bank and Account classes to
case classes
Remove vals, new, try out the toString, equals etc

Recommended for you

Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010

Scala is a programming language that combines object-oriented and functional programming. It runs on the JVM and is interoperable with Java. Scala is statically typed and concise. Scala allows modeling of concepts like rational numbers and mutable cells. Classes can implement traits to mix in functionality like logging. Pattern matching makes deconstructing data structures like lists and optional values easy. The Scala library includes collections, functions, and other functional programming constructs.

scala
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should care

Data types. Type checking. IO data parsing. Immutability. Persistent data structures. Immutable languages.

type checkingimmutabilityfunctional programming
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf

Presented at Gartner Data & Analytics, London Maty 2024. BT Group has used the Neo4j Graph Database to enable impressive digital transformation programs over the last 6 years. By re-imagining their operational support systems to adopt self-serve and data lead principles they have substantially reduced the number of applications and complexity of their operations. The result has been a substantial reduction in risk and costs while improving time to value, innovation, and process automation. Join this session to hear their story, the lessons they learned along the way and how their future innovation plans include the exploration of uses of EKG + Generative AI.

neo4jneo4j webinarsgraph database
Knoldus
Functional Objects
Are objects that do not have mutable state
Knoldus
What does it mean?
1/2 + 5/6 = 8/6
Rational numbers do not have mutable state
When we add two rational numbers we get a new rational
number back
Knoldus
Why immutability is good?
Easier to reason Since there are no complex
state spaces that change over
time
Pass around freely
2 threads cannot corrupt
Make safe hashtable keys
Whereas for mutable objects
we need to make defensive
copies first
Once constructed, no-one can
change it
A mutable object may not be
found in the same hashset
once its state is mutated
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching

Recommended for you

How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx

Revolutionize your transportation processes with our cutting-edge RPA software. Automate repetitive tasks, reduce costs, and enhance efficiency in the logistics sector with our advanced solutions.

rpa in transportationrpa in transportation industryrpa in transportation sector
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition

The DealBook is our annual overview of the Ukrainian tech investment industry. This edition comprehensively covers the full year 2023 and the first deals of 2024.

Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM

Quantum Communications Q&A with Gemini LLM. These are based on Shannon's Noisy channel Theorem and offers how the classical theory applies to the quantum world.

quantum communicationsshannon's channel theoremclassical theory
Knoldus
Built in control structures
Almost all Scala control structures would result in
a value
Without this programs must create temporary
variables to hold values calculated inside control
structures
Knoldus
● Conventional way
● Scala way
var fileName = "default.txt"
if (1 < 2) fileName = "newDefault.txt"
val fileNameNew = if (1<2) "newDefault.txt" else "default.txt"
Using val
Knoldus
Are called loops and
Not expressions because
They do not result in a value
Usually left out of functional
programming
Knoldus
For expression
Without a yield does not result in a value
for (l <- List(1,2,3,4)) yield if (l%2==0) l else 1
//
> res10: List[Int] = List(1, 2, 1, 4)
With a yield
returns a value

Recommended for you

The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses

CIO Council Cal Poly Humboldt September 22, 2023

national research platformdistributed supercomputerdistributed systems
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges

accommodate the strengths, weaknesses, threats and opportunities of autonomous vehicles

automotive self-driving car technology
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world

The presentation showcases the diverse real-world applications of Fused Deposition Modeling (FDM) across multiple industries: 1. **Manufacturing**: FDM is utilized in manufacturing for rapid prototyping, creating custom tools and fixtures, and producing functional end-use parts. Companies leverage its cost-effectiveness and flexibility to streamline production processes. 2. **Medical**: In the medical field, FDM is used to create patient-specific anatomical models, surgical guides, and prosthetics. Its ability to produce precise and biocompatible parts supports advancements in personalized healthcare solutions. 3. **Education**: FDM plays a crucial role in education by enabling students to learn about design and engineering through hands-on 3D printing projects. It promotes innovation and practical skill development in STEM disciplines. 4. **Science**: Researchers use FDM to prototype equipment for scientific experiments, build custom laboratory tools, and create models for visualization and testing purposes. It facilitates rapid iteration and customization in scientific endeavors. 5. **Automotive**: Automotive manufacturers employ FDM for prototyping vehicle components, tooling for assembly lines, and customized parts. It speeds up the design validation process and enhances efficiency in automotive engineering. 6. **Consumer Electronics**: FDM is utilized in consumer electronics for designing and prototyping product enclosures, casings, and internal components. It enables rapid iteration and customization to meet evolving consumer demands. 7. **Robotics**: Robotics engineers leverage FDM to prototype robot parts, create lightweight and durable components, and customize robot designs for specific applications. It supports innovation and optimization in robotic systems. 8. **Aerospace**: In aerospace, FDM is used to manufacture lightweight parts, complex geometries, and prototypes of aircraft components. It contributes to cost reduction, faster production cycles, and weight savings in aerospace engineering. 9. **Architecture**: Architects utilize FDM for creating detailed architectural models, prototypes of building components, and intricate designs. It aids in visualizing concepts, testing structural integrity, and communicating design ideas effectively. Each industry example demonstrates how FDM enhances innovation, accelerates product development, and addresses specific challenges through advanced manufacturing capabilities.

fdmffffused deposition modeling
Knoldus
Try Catch
In Scala all exceptions are unchecked exceptions and we
need not catch any exception explicitly.
Technically an Exception throw is of the type Nothing
val n = 11
import java.io.FileNotFoundException
try {
val bb = if (n % 2 == 0) n / 2 else throw new Exception
} catch {
case ex: FileNotFoundException => // Missing file
case ex: Exception => println("caught exception")
} //> caught exception
Knoldus
Match Expression
Unlike Java's Switch statement, match expression results in a value
val matchValue = n match {
case 11 => "eleven"
case _ => "I dont know"
}
//> matchValue : java.lang.String = eleven
println(matchValue)
Knoldus
Functions
Allow us to code the functionality of the system
Most Functions are member of some object
Functions can be nested within other functions
We can define function literals and function values
Knoldus
Regular

Recommended for you

Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...

Today’s digitally connected world presents a wide range of security challenges for enterprises. Insider security threats are particularly noteworthy because they have the potential to cause significant harm. Unlike external threats, insider risks originate from within the company, making them more subtle and challenging to identify. This blog aims to provide a comprehensive understanding of insider security threats, including their types, examples, effects, and mitigation techniques.

insider securitycybersecurity threatsenterprise security
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides

If you’ve ever had to analyze a map or GPS data, chances are you’ve encountered and even worked with coordinate systems. As historical data continually updates through GPS, understanding coordinate systems is increasingly crucial. However, not everyone knows why they exist or how to effectively use them for data-driven insights. During this webinar, you’ll learn exactly what coordinate systems are and how you can use FME to maintain and transform your data’s coordinate systems in an easy-to-digest way, accurately representing the geographical space that it exists within. During this webinar, you will have the chance to: - Enhance Your Understanding: Gain a clear overview of what coordinate systems are and their value - Learn Practical Applications: Why we need datams and projections, plus units between coordinate systems - Maximize with FME: Understand how FME handles coordinate systems, including a brief summary of the 3 main reprojectors - Custom Coordinate Systems: Learn how to work with FME and coordinate systems beyond what is natively supported - Look Ahead: Gain insights into where FME is headed with coordinate systems in the future Don’t miss the opportunity to improve the value you receive from your coordinate system data, ultimately allowing you to streamline your data analysis and maximize your time. See you there!

Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf

Sustainability requires ingenuity and stewardship. Did you know Pigging Solutions pigging systems help you achieve your sustainable manufacturing goals AND provide rapid return on investment. How? Our systems recover over 99% of product in transfer piping. Recovering trapped product from transfer lines that would otherwise become flush-waste, means you can increase batch yields and eliminate flush waste. From raw materials to finished product, if you can pump it, we can pig it.

pigging solutionsprocess piggingproduct transfers
Knoldus
Local
Not accessible
outside
Knoldus
Function Literals
Functions can be written as unnamed function literals
and passed as values!
Function literal
in source code
Compiled to
Function value
at runtime
Knoldus
(x:Int)=> x * 2
Is a valid function literal, it can be
Assigned to a variable
Passed in another function
Knoldus
val multiply = (x:Int) => x * 2
multiply (20) //> res11: Int = 40
multiply (25) //> res12: Int = 50
Function literals can be assigned to variables

Recommended for you

Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time

Is your patent a vanity piece of paper for your office wall? Or is it a reliable, defendable, assertable, property right? The difference is often quality. Is your patent simply a transactional cost and a large pile of legal bills for your startup? Or is it a leverageable asset worthy of attracting precious investment dollars, worth its cost in multiples of valuation? The difference is often quality. Is your patent application only good enough to get through the examination process? Or has it been crafted to stand the tests of time and varied audiences if you later need to assert that document against an infringer, find yourself litigating with it in an Article 3 Court at the hands of a judge and jury, God forbid, end up having to defend its validity at the PTAB, or even needing to use it to block pirated imports at the International Trade Commission? The difference is often quality. Quality will be our focus for a good chunk of the remainder of this season. What goes into a quality patent, and where possible, how do you get it without breaking the bank? ** Episode Overview ** In this first episode of our quality series, Kristen Hansen and the panel discuss: ⦿ What do we mean when we say patent quality? ⦿ Why is patent quality important? ⦿ How to balance quality and budget ⦿ The importance of searching, continuations, and draftsperson domain expertise ⦿ Very practical tips, tricks, examples, and Kristen’s Musts for drafting quality applications https://www.aurorapatents.com/patently-strategic-podcast.html

patentspatent applicationpatent prosecution
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In

Six months into 2024, and it is clear the privacy ecosystem takes no days off!! Regulators continue to implement and enforce new regulations, businesses strive to meet requirements, and technology advances like AI have privacy professionals scratching their heads about managing risk. What can we learn about the first six months of data privacy trends and events in 2024? How should this inform your privacy program management for the rest of the year? Join TrustArc, Goodwin, and Snyk privacy experts as they discuss the changes we’ve seen in the first half of 2024 and gain insight into the concrete, actionable steps you can take to up-level your privacy program in the second half of the year. This webinar will review: - Key changes to privacy regulations in 2024 - Key themes in privacy and data governance in 2024 - How to maximize your privacy program in the second half of 2024

data privacyprivacy complianceai
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces

An invited talk given by Mark Billinghurst on Research Directions for Cross Reality Interfaces. This was given on July 2nd 2024 as part of the 2024 Summer School on Cross Reality in Hagenberg, Austria (July 1st - 7th)

augmented realitycross realityvirtual reality
Knoldus
Short forms for function literals works when the
compiler can infer what it would be
List(1,2,3) foreach ((x)=>x*2)
val multiply = (x) => x * 2
This would fail
Knoldus
Placeholder syntax, if the parameter appears
only one time within the function literal
List(1,2,3) foreach (_*2)
List(1,2,3) foreach ((x)=>x*2)
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Class Inheritance
class Animal
class Dog extends Animal
Omitting the extends keyword means that we are extending from
AnyRef

Recommended for you

Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024

This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator. Link to presentation recording and transcript: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/ Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.

a11yaccessibilityalt text
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024

Everything that I found interesting about engineering leadership last month

quantumfaxmachine
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry

Are you interested in dipping your toes in the cloud native observability waters, but as an engineer you are not sure where to get started with tracing problems through your microservices and application landscapes on Kubernetes? Then this is the session for you, where we take you on your first steps in an active open-source project that offers a buffet of languages, challenges, and opportunities for getting started with telemetry data. The project is called openTelemetry, but before diving into the specifics, we’ll start with de-mystifying key concepts and terms such as observability, telemetry, instrumentation, cardinality, percentile to lay a foundation. After understanding the nuts and bolts of observability and distributed traces, we’ll explore the openTelemetry community; its Special Interest Groups (SIGs), repositories, and how to become not only an end-user, but possibly a contributor.We will wrap up with an overview of the components in this project, such as the Collector, the OpenTelemetry protocol (OTLP), its APIs, and its SDKs. Attendees will leave with an understanding of key observability concepts, become grounded in distributed tracing terminology, be aware of the components of openTelemetry, and know how to take their first steps to an open-source contribution! Key Takeaways: Open source, vendor neutral instrumentation is an exciting new reality as the industry standardizes on openTelemetry for observability. OpenTelemetry is on a mission to enable effective observability by making high-quality, portable telemetry ubiquitous. The world of observability and monitoring today has a steep learning curve and in order to achieve ubiquity, the project would benefit from growing our contributor community.

cloudcloud native observabilitycloud native
Knoldus
class Animal(name:String)
class Dog(name:String) extends Animal(name)
Subclasses must immediately call the superclass constructor
Calling it without the super class constructor would not work
Knoldus
final class Animal(name:String)
class Dog(name:String) extends Animal(name)
Defining the class as final restricts it from being subclassed
Knoldus
class Animal(name: String) {
val kind = "carnivorous"
}
class Dog(name: String) extends Animal(name) {
override val kind = "vegetarian"
}
class Dog(name: String) extends Animal(name) {
override val kind = "vegetarian"
override val dangerous = true
}
Complains that it
overrides nothing
Hence helps us with
warning
Knoldus
Abstract class
Omitting an
initialization or
implementation would
have to make a class
abstract
Cannot be initialized, they need to be
subclassed

Recommended for you

Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...

This presentation explores the practical application of image description techniques. Familiar guidelines will be demonstrated in practice, and descriptions will be developed “live”! If you have learned a lot about the theory of image description techniques but want to feel more confident putting them into practice, this is the presentation for you. There will be useful, actionable information for everyone, whether you are working with authors, colleagues, alone, or leveraging AI as a collaborator. Link to presentation recording and slides: https://bnctechforum.ca/sessions/details-of-description-part-ii-describing-images-in-practice/ Presented by BookNet Canada on June 25, 2024, with support from the Department of Canadian Heritage.

a11yaccessibilityalt text
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf

To help you choose the best DiskWarrior alternative, we've compiled a comparison table summarizing the features, pros, cons, and pricing of six alternatives.

data recoverydatadiskwarrior
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL

Blockchain technology is transforming industries and reshaping the way we conduct business, manage data, and secure transactions. Whether you're new to blockchain or looking to deepen your knowledge, our guidebook, "Blockchain for Dummies", is your ultimate resource.

blockchainweb3blockchain technology
Knoldus
Scala Hierarchy
● All classes extend from a common superclass
called Any
● Methods of Any are universal methods
● Null and Nothing are common subclasses at
the bottom of the hierarchy
Knoldus
Knoldus
Any
AnyVal AnyRef
Byte
Short
Char
Int
Long
Float
Double
Boolean
Unit
Instances of these
classes are written as
literals in Scala
42
Not new Int
AnyRef is a an alias
for java.lang.Object
All Scala classes also
inherit from special
marker trait called
ScalaObject which
makes execution of
Scala programs
efficient
Knoldus

Recommended for you

[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf

Kief Morris rethinks the infrastructure code delivery lifecycle, advocating for a shift towards composable infrastructure systems. We should shift to designing around deployable components rather than code modules, use more useful levels of abstraction, and drive design and deployment from applications rather than bottom-up, monolithic architecture and delivery.

infrastructure as codeclouddevops
Knoldus
Traits
Fundamental unit of code reuse in Scala
A class can mix in any number of traits but inherit from one
SuperClass
Knoldus
We can use it as
variable of type
Philosophical
Knoldus
Traits
Declare fields
Can have state
Define functionality
Anything that can be done in
class definition can be done in
trait definition as well
Cannot have class parameters
(which are passed to primary
constructor of class)
Super calls are dynamically
bound
Knoldus
Rich Interface
Has many methods, which makes
it convenient for caller
Thin Interface
Has less methods which
makes it easy for
implementors
Scala allows adding concrete implementations in traits which makes it suitable
for Rich interfaces + methods which need to be implemented by implementors
which is like a thin interface as well

Recommended for you

Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
Agenda
● Scala Who & Why?
● First Steps
● Classes and Objects
● Control Structures
and Functions
● Inheritance and
Traits
● Pattern Matching
Knoldus
General Syntax
Matching order is top
to bottom
No need to give
break
As soon as the first
match is executed, it
breaks
If a pattern matches, result is given. If no pattern
matches then MatchError is thrown
Knoldus
Wildcard pattern
val name = "vikas"
name match {
case "Sachin" => println("Sud")
case "Virender" => println("Virender")
case "Dhoni" => println("Dhoni")
case "Vikas" => println("Vikas")
case _ => println("Nothing matched")
}
Put wildcard match as the last alternative to prevent
MatchError
Wildcard match

Recommended for you

Knoldus
Copyright (c) 2013-14 Knoldus
Software LLP
This training material is only intended to be used by
people attending the Knoldus Scala training.
Unauthorized reproduction, redistribution, or use
of this material is strictly prohibited.

More Related Content

What's hot

Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
輝 子安
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
Ruslan Shevchenko
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Xebia IT Architects
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
All about scala
All about scalaAll about scala
All about scala
Yardena Meymann
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
Roberto Casadei
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Scala Intro
Scala IntroScala Intro
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Paolo Platter
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
Ruslan Shevchenko
 

What's hot (20)

Scala for Java programmers
Scala for Java programmersScala for Java programmers
Scala for Java programmers
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
All about scala
All about scalaAll about scala
All about scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Programming in Scala: Notes
Programming in Scala: NotesProgramming in Scala: Notes
Programming in Scala: Notes
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 

Viewers also liked

Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
Yardena Meymann
 
Akka -- Scalability in Scala and Java
Akka -- Scalability in Scala and JavaAkka -- Scalability in Scala and Java
Akka -- Scalability in Scala and Java
Nadav Wiener
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
Alex Payne
 
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013
Matt Raible
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
Yevgeniy Brikman
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
Sander Mak (@Sander_Mak)
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
nartamonov
 

Viewers also liked (7)

Concurrency in Scala - the Akka way
Concurrency in Scala - the Akka wayConcurrency in Scala - the Akka way
Concurrency in Scala - the Akka way
 
Akka -- Scalability in Scala and Java
Akka -- Scalability in Scala and JavaAkka -- Scalability in Scala and Java
Akka -- Scalability in Scala and Java
 
The Why and How of Scala at Twitter
The Why and How of Scala at TwitterThe Why and How of Scala at Twitter
The Why and How of Scala at Twitter
 
Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013Comparing JVM Web Frameworks - Devoxx France 2013
Comparing JVM Web Frameworks - Devoxx France 2013
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
Above the clouds: introducing Akka
Above the clouds: introducing AkkaAbove the clouds: introducing Akka
Above the clouds: introducing Akka
 

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

Scala ntnu
Scala ntnuScala ntnu
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
CodeOps Technologies LLP
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
Jakub Kahovec
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
Pamela Fox
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
Radoslav Georgiev
 
(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
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
Riccardo Cardin
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
Amuhinda Hungai
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should care
Jean Carlo Emer
 

Similar to Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organized by Knoldus Software LLP in New Delhi (20)

Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Interpreter Case Study - Design Patterns
Interpreter Case Study - Design PatternsInterpreter Case Study - Design Patterns
Interpreter Case Study - Design Patterns
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
(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?
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Introductiontoprogramminginscala
IntroductiontoprogramminginscalaIntroductiontoprogramminginscala
Introductiontoprogramminginscala
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
Types and Immutability: why you should care
Types and Immutability: why you should careTypes and Immutability: why you should care
Types and Immutability: why you should care
 

Recently uploaded

BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
Yevgen Sysoyev
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
Vijayananda Mohire
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
Mark Billinghurst
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
Kief Morris
 

Recently uploaded (20)

BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
DealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 editionDealBook of Ukraine: 2024 edition
DealBook of Ukraine: 2024 edition
 
Quantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLMQuantum Communications Q&A with Gemini LLM
Quantum Communications Q&A with Gemini LLM
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Research Directions for Cross Reality Interfaces
Research Directions for Cross Reality InterfacesResearch Directions for Cross Reality Interfaces
Research Directions for Cross Reality Interfaces
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
[Talk] Moving Beyond Spaghetti Infrastructure [AOTB] 2024-07-04.pdf
 

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

  • 3. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 4. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 5. Knoldus In 2003, Martin Odersky and his team set out to create a “scalable” language that fused important concepts from functional and object-oriented programming. The language aimed to be highly interoperable with Java, have a rich type system, and to allow developers to express powerful concepts concisely.
  • 8. Knoldus Functional programming contructs make it easy to build interesting things quickly from small parts Object oriented constructs make it easy to structure large systems and adapt to new demands
  • 9. Knoldus Object oriented Everything is an object, pure OO Not like java where we have primitives / static fields and methods which are not members of any object 1+2 is actually 1.+(2) 1 + 2 //> res1: Int(3) = 3 1 .+(2) //> res2: Int(3) = 3
  • 10. Knoldus Functional language Functions are first class values Encourages immutability where operations map input values to output rather than change data in place
  • 12. Knoldus Expressive val numbers = 1 to 10 //>Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers filter { _ % 2 == 0 } //> Vector(2, 4, 6, 8, 10)
  • 13. Knoldus High Level Finding an upper case character
  • 14. Knoldus Statically Typed Verifiable Properties Safe Refactorings Documentation Cannot add boolean to List[Int] Strong type inference val x = Map(1->”somevalue”)
  • 15. Knoldus 1. Create a new worksheet called Lab1 2. Print “Hello Scala World” 3. See the program execute in Worksheet
  • 16. Knoldus 1 + 2 What do you see? /> res1: Int(3) = 3
  • 17. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 19. Knoldus Why does this code compile? Type Inference val msg:String = "Hello World!" //> msg : String = Hello World!
  • 20. Knoldus Sometimes variables need to mutate var description = "start" > description : java.lang.String = start description = "end"
  • 22. Knoldus Unit A result of Unit indicates that the function returns no interesting value def justGreet(name:String) = println("Hello " + name) //> justGreet: (name: String)Unit Similar to void in Java
  • 23. Knoldus Everything returns a value val number = { val x: Int = 7 val y: Int = 9 x + y } //> number : Int = 16 if (1 < 10) 15 else 17
  • 24. Knoldus Everything returns a value val number = { val x: Int = 7 val y: Int = 9 x + y } //> number : Int = 16 if (1 < 10) 15 else 17
  • 25. Knoldus Functions, first look List(1,2,3).foreach(l=>println(l)) List(1,2,3).foreach(l=>println(l)) List(1,2,3).foreach(println(_)) List(1,2,3) foreach (println(_)) List(1,2,3) foreach (println) List(1,2,3) foreach println Foreach takes a function of what needs to be done List(1,2,3) foreach ((x:Int)=>println(2*x))
  • 26. Knoldus Function Literal What we pass inside of foreach is a function literal List(1,2,3) foreach ((x:Int)=>println(2*x))
  • 27. Knoldus Working with Arrays val greetStrings = new Array[String](3) //> greetStrings : Array[String] = Array(null, null, null) greetStrings(0) = "Bank" greetStrings(1) = "of" greetStrings(2) = "America" greetStrings(0) = "BANK" Notice? val greetStrings = List(1,2,3) greetStrings(0) = "Bank" greetStrings(1) = "of" greetStrings(2) = "America" greetStrings(0) = "BANK"
  • 32. Knoldus Tuples Immutable like lists, but can have different types of elements Why we cannot get values out of a Tuple just like list?
  • 33. Knoldus Sets and Maps By default, we are provided with the immutable collections
  • 34. Knoldus What is happening here var treasureMap = Map(1->"a", 2->"b") treasureMap += (3->"c") What happens if we change treasureMap to val? Why?
  • 35. Knoldus Understanding Functional Style No vars No methods with side effects – Unit No while loops
  • 36. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 37. Knoldus Singleton objects ● A singleton object is like a class and its sole instance ● Use the keyword object to define a singleton object: object Foo { val bar = "Bar" } Access singleton objects like Foo.bar
  • 39. Knoldus Classes ● Classes are blueprints for objects ● class Bank – is a valid class definition No Semicolon No access modifier, public by default No curly braces since no body Create a new instance new Bank
  • 40. Knoldus class Bank(id:Int, name:String) new Bank(1,"BoA") //> res5: lab1.Bank = lab1$anonfun$main$1$Bank$1@1372a7a Parameters are val and cannot be accessed from outside
  • 41. Knoldus class Bank(id:Int, name:String) val b = new Bank(1,"BoA") b.id
  • 42. Knoldus class Bank(id:Int, name:String) val b = new Bank(1,"BoA") b.id
  • 43. Knoldus Add another parameter to bank Create another instance of bank
  • 44. Knoldus Auxilliary Constructors class Bank(id: Int, name: String) { def this(str: String) = this(1, str) def this() = this(1, "") } Must immediately call another constructor with this
  • 45. Knoldus Accessing fields of a class class Bank(id: Int, name: String) { val kind = "Blue" var address = "Delhi" def this(str: String) = this(1, str) def this() = this(1, "") } val b = new Bank(1, "BoA") b.address = "Mumbai" b.kind = "op" immutable mutable
  • 46. Knoldus Making fields from class parameters class Bank(val id: Int, var name: String) { val kind = "Blue" var address = "Delhi" def this(str: String) = this(1, str) def this() = this(1, "") } See if you can access id and name outside the class now
  • 47. Knoldus Make a Bank class with the following immutable parameters Id, name, address, city Create a bank instance and access its fields Make a Account class with the following immutable parameters Id, name, amount Create a Account instance and access its fields
  • 48. Knoldus Define a debit method in the Account class def debit(amount:Int):Int = {...}
  • 49. Knoldus class Account(id: Int, name: String, amount: Int) { def debit(debitAmount: Int): Int = amount - debitAmount def -(debitAmount: Int): Int = amount - debitAmount } new Account(1, "VikasAccount", 100) - 20 //
  • 50. Knoldus Default Parameters class Account(id: Int, name: String, amount: Int = 0) { def debit(debitAmount: Int): Int = amount - debitAmount def -(debitAmount: Int): Int = amount - debitAmount } With default parameters, new Account(1,"Another")
  • 51. Knoldus Singleton objects ● A singleton object is like a class and its sole instance ● Use the keyword object to define a singleton object: object Foo { val bar = "Bar" } Access singleton objects like Foo.bar
  • 52. Knoldus Singleton Objects ● Can be thought to be like static in Java but these are real objects which can inherit and be passed around
  • 53. Knoldus Companion Objects ● If a singleton object and a class or trait share the same name, package and file, they are called companions class Bank(val id: Int, var name: String) { private val kind = "Blue" var address = "Delhi" + Bank.city def this(str: String) = this(1, str) def this() = this(1, "") } object Bank { private val city = "Delhi" val newBank = new Bank(1,"ABC") newBank.kind } Class or trait can access private member of Companion object
  • 54. Knoldus Create a companion object for Account Create a method in account object to get the type of account like Saving or Checking Or Any other method that you like
  • 55. Knoldus Understanding Predef Predef object provides definitions which are accessible in all Scala compilation units without explicit qualification Aliases for types such as Map, Set and List Assertions – Require and Ensuring Console IO – such as print, println, readLine, readInt. These methods are otherwise provided by scala.Console
  • 56. Knoldus Add a require assertion to the account that id has to be > 0 Add any other preconditions for accounts
  • 57. Knoldus class Bank(val id: Int, var name: String) { require(id > 0) private val kind = "Blue" var address = "Delhi" Bank.city def this(str: String) = this(1, str) def this() = this(1, "") } object Bank { val city = "Delhi" val newBank = new Bank(1, "ABC") } new Bank(0,"ll") //> java.lang.IllegalArgumentException: requirement failed
  • 58. Knoldus Case Classes Add syntactic convenience to your class Add factory method with Name of class so we don't Need to do new All parameters in the Parameter list get a val by default Natural implementation of toString, hashCode and equals to the class Support pattern matching Small price In terms of Size
  • 59. Knoldus case class Bird(name: String) val b = Bird("pigeon") //> b : lab1.Bird = Bird(pigeon) val c = Bird("pigeon") //> c : lab1.Bird = Bird(pigeon) b == c //> res7: Boolean = true
  • 60. Knoldus Try converting the Bank and Account classes to case classes Remove vals, new, try out the toString, equals etc
  • 61. Knoldus Functional Objects Are objects that do not have mutable state
  • 62. Knoldus What does it mean? 1/2 + 5/6 = 8/6 Rational numbers do not have mutable state When we add two rational numbers we get a new rational number back
  • 63. Knoldus Why immutability is good? Easier to reason Since there are no complex state spaces that change over time Pass around freely 2 threads cannot corrupt Make safe hashtable keys Whereas for mutable objects we need to make defensive copies first Once constructed, no-one can change it A mutable object may not be found in the same hashset once its state is mutated
  • 64. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 65. Knoldus Built in control structures Almost all Scala control structures would result in a value Without this programs must create temporary variables to hold values calculated inside control structures
  • 66. Knoldus ● Conventional way ● Scala way var fileName = "default.txt" if (1 < 2) fileName = "newDefault.txt" val fileNameNew = if (1<2) "newDefault.txt" else "default.txt" Using val
  • 67. Knoldus Are called loops and Not expressions because They do not result in a value Usually left out of functional programming
  • 68. Knoldus For expression Without a yield does not result in a value for (l <- List(1,2,3,4)) yield if (l%2==0) l else 1 // > res10: List[Int] = List(1, 2, 1, 4) With a yield returns a value
  • 69. Knoldus Try Catch In Scala all exceptions are unchecked exceptions and we need not catch any exception explicitly. Technically an Exception throw is of the type Nothing val n = 11 import java.io.FileNotFoundException try { val bb = if (n % 2 == 0) n / 2 else throw new Exception } catch { case ex: FileNotFoundException => // Missing file case ex: Exception => println("caught exception") } //> caught exception
  • 70. Knoldus Match Expression Unlike Java's Switch statement, match expression results in a value val matchValue = n match { case 11 => "eleven" case _ => "I dont know" } //> matchValue : java.lang.String = eleven println(matchValue)
  • 71. Knoldus Functions Allow us to code the functionality of the system Most Functions are member of some object Functions can be nested within other functions We can define function literals and function values
  • 74. Knoldus Function Literals Functions can be written as unnamed function literals and passed as values! Function literal in source code Compiled to Function value at runtime
  • 75. Knoldus (x:Int)=> x * 2 Is a valid function literal, it can be Assigned to a variable Passed in another function
  • 76. Knoldus val multiply = (x:Int) => x * 2 multiply (20) //> res11: Int = 40 multiply (25) //> res12: Int = 50 Function literals can be assigned to variables
  • 77. Knoldus Short forms for function literals works when the compiler can infer what it would be List(1,2,3) foreach ((x)=>x*2) val multiply = (x) => x * 2 This would fail
  • 78. Knoldus Placeholder syntax, if the parameter appears only one time within the function literal List(1,2,3) foreach (_*2) List(1,2,3) foreach ((x)=>x*2)
  • 79. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 80. Knoldus Class Inheritance class Animal class Dog extends Animal Omitting the extends keyword means that we are extending from AnyRef
  • 81. Knoldus class Animal(name:String) class Dog(name:String) extends Animal(name) Subclasses must immediately call the superclass constructor Calling it without the super class constructor would not work
  • 82. Knoldus final class Animal(name:String) class Dog(name:String) extends Animal(name) Defining the class as final restricts it from being subclassed
  • 83. Knoldus class Animal(name: String) { val kind = "carnivorous" } class Dog(name: String) extends Animal(name) { override val kind = "vegetarian" } class Dog(name: String) extends Animal(name) { override val kind = "vegetarian" override val dangerous = true } Complains that it overrides nothing Hence helps us with warning
  • 84. Knoldus Abstract class Omitting an initialization or implementation would have to make a class abstract Cannot be initialized, they need to be subclassed
  • 85. Knoldus Scala Hierarchy ● All classes extend from a common superclass called Any ● Methods of Any are universal methods ● Null and Nothing are common subclasses at the bottom of the hierarchy
  • 87. Knoldus Any AnyVal AnyRef Byte Short Char Int Long Float Double Boolean Unit Instances of these classes are written as literals in Scala 42 Not new Int AnyRef is a an alias for java.lang.Object All Scala classes also inherit from special marker trait called ScalaObject which makes execution of Scala programs efficient
  • 89. Knoldus Traits Fundamental unit of code reuse in Scala A class can mix in any number of traits but inherit from one SuperClass
  • 90. Knoldus We can use it as variable of type Philosophical
  • 91. Knoldus Traits Declare fields Can have state Define functionality Anything that can be done in class definition can be done in trait definition as well Cannot have class parameters (which are passed to primary constructor of class) Super calls are dynamically bound
  • 92. Knoldus Rich Interface Has many methods, which makes it convenient for caller Thin Interface Has less methods which makes it easy for implementors Scala allows adding concrete implementations in traits which makes it suitable for Rich interfaces + methods which need to be implemented by implementors which is like a thin interface as well
  • 93. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 94. Knoldus Agenda ● Scala Who & Why? ● First Steps ● Classes and Objects ● Control Structures and Functions ● Inheritance and Traits ● Pattern Matching
  • 95. Knoldus General Syntax Matching order is top to bottom No need to give break As soon as the first match is executed, it breaks If a pattern matches, result is given. If no pattern matches then MatchError is thrown
  • 96. Knoldus Wildcard pattern val name = "vikas" name match { case "Sachin" => println("Sud") case "Virender" => println("Virender") case "Dhoni" => println("Dhoni") case "Vikas" => println("Vikas") case _ => println("Nothing matched") } Put wildcard match as the last alternative to prevent MatchError Wildcard match
  • 97. Knoldus Copyright (c) 2013-14 Knoldus Software LLP This training material is only intended to be used by people attending the Knoldus Scala training. Unauthorized reproduction, redistribution, or use of this material is strictly prohibited.