This document provides an introduction to the Scala programming language. It begins with a brief history of Scala and overview of its core concepts like vals, classes, objects, traits, and functions. It also covers intermediate concepts like pattern matching, Option, XML and Futures. The document discusses Scala's support for functional and object-oriented programming and how it compiles to Java bytecode. It provides examples of using Scala's collections and control structures and describes features like classes, objects, traits and case classes.
This is brief presentation on the Scala programming language. It is aimed at Java developers who are curious about Scala. It was given at a San Francisco Java User Group in January 2009.
The document compares and contrasts features of the Scala and Ruby programming languages, including type systems, pattern matching, monkey patching, dynamic calls, traits/modules, and more. It discusses how each language handles the given features, often providing code examples, and notes similarities and differences between the two approaches. The overall assessment is that a draw is the best way to characterize the comparison between Scala and Ruby, as both languages have their merits for different use cases and preferences.
This document discusses new features in ECMAScript (ES) 6 including: enhanced object literals with shorthand property and method definitions; destructuring assignment for arrays and objects; template strings for string interpolation; iterators, generators, and for-of loops; modules with named and default exports; and the module loader API. It provides code examples to demonstrate these new features and compares them to CommonJS and ES5 syntax.
Intro to Functional Programming in ScalaShai Yallin
Scala is a functional and object-oriented programming language that runs on the Java Virtual Machine. It features type inference, immutable collections, pattern matching, and functions as first-class values. The document provides an overview of Scala's features such as its static typing, traits for multiple inheritance, and case classes for value objects. It also demonstrates Scala's collections API and use of functions and pattern matching.
This document discusses porting a Java library for distributed object coordination called Fly to Scala. The port involved syntactic conversion to Scala, using more idiomatic Scala APIs, adopting Scala idioms internally, leveraging actors, and comparing Java and Scala. Overall, the Scala version was 60% shorter due to better abstractions for common algorithms. Future work could include implementing the library from scratch with a more functional design.
Realm is a relatively new database that is increasingly being used by iOS developers. It offers benefits over SQLite and Core Data like being faster and more efficient. Realm models are defined as Swift classes that function like regular objects. Objects can be created, updated, deleted, and queried using Realm similar to how it's done with CoreData and SQLite but with improved performance. The presentation demonstrated how to implement basic CRUD operations and querying with Realm in an iOS app.
Part of a series of talk to help you write your first Perl 6 program today. So its basic syntax and concepts of its object orientation and a comparison to the widely used P5 OO system Moose which is similar by no accident.
As a full-time Scala developer, I often find myself talking about Scala and functional programming in different kinds of situations, ranging from meeting a friend working in J2EE, Ruby or C++, to dedicated Scala Meetups aiming to promote deeper understanding of the language. However, something occurred to me lately. By hanging out with people who have some Scala knowledge or experience, I am somewhat holding on to a safe place. By presenting only to people who are curious about Scala, I'm preaching to the converted.
To make a long story short, I recently made an attempt at getting out of my comfort zone by presenting about how making the transition from Java to Scala makes total sense (from Java developer point of view). The presentation went through proof-hearing of approximately 60 experienced Java programmers (with almost no prior Scala knowledge) gathered in one room for a Lunch & Learn. Here are my slides.
This is brief presentation on the Scala programming language. It is aimed at Java developers who are curious about Scala. It was given at a San Francisco Java User Group in January 2009.
The document compares and contrasts features of the Scala and Ruby programming languages, including type systems, pattern matching, monkey patching, dynamic calls, traits/modules, and more. It discusses how each language handles the given features, often providing code examples, and notes similarities and differences between the two approaches. The overall assessment is that a draw is the best way to characterize the comparison between Scala and Ruby, as both languages have their merits for different use cases and preferences.
This document discusses new features in ECMAScript (ES) 6 including: enhanced object literals with shorthand property and method definitions; destructuring assignment for arrays and objects; template strings for string interpolation; iterators, generators, and for-of loops; modules with named and default exports; and the module loader API. It provides code examples to demonstrate these new features and compares them to CommonJS and ES5 syntax.
Intro to Functional Programming in ScalaShai Yallin
Scala is a functional and object-oriented programming language that runs on the Java Virtual Machine. It features type inference, immutable collections, pattern matching, and functions as first-class values. The document provides an overview of Scala's features such as its static typing, traits for multiple inheritance, and case classes for value objects. It also demonstrates Scala's collections API and use of functions and pattern matching.
This document discusses porting a Java library for distributed object coordination called Fly to Scala. The port involved syntactic conversion to Scala, using more idiomatic Scala APIs, adopting Scala idioms internally, leveraging actors, and comparing Java and Scala. Overall, the Scala version was 60% shorter due to better abstractions for common algorithms. Future work could include implementing the library from scratch with a more functional design.
Realm is a relatively new database that is increasingly being used by iOS developers. It offers benefits over SQLite and Core Data like being faster and more efficient. Realm models are defined as Swift classes that function like regular objects. Objects can be created, updated, deleted, and queried using Realm similar to how it's done with CoreData and SQLite but with improved performance. The presentation demonstrated how to implement basic CRUD operations and querying with Realm in an iOS app.
Part of a series of talk to help you write your first Perl 6 program today. So its basic syntax and concepts of its object orientation and a comparison to the widely used P5 OO system Moose which is similar by no accident.
As a full-time Scala developer, I often find myself talking about Scala and functional programming in different kinds of situations, ranging from meeting a friend working in J2EE, Ruby or C++, to dedicated Scala Meetups aiming to promote deeper understanding of the language. However, something occurred to me lately. By hanging out with people who have some Scala knowledge or experience, I am somewhat holding on to a safe place. By presenting only to people who are curious about Scala, I'm preaching to the converted.
To make a long story short, I recently made an attempt at getting out of my comfort zone by presenting about how making the transition from Java to Scala makes total sense (from Java developer point of view). The presentation went through proof-hearing of approximately 60 experienced Java programmers (with almost no prior Scala knowledge) gathered in one room for a Lunch & Learn. Here are my slides.
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar that makes JavaScript cleaner and adds features inspired by Python and Ruby. Key features include cleaner syntax for functions, objects, conditionals, loops, and classes. CoffeeScript code compiles directly to equivalent JavaScript code, so it can be used anywhere JavaScript is used like web browsers and Node.js. To use CoffeeScript, install the CoffeeScript compiler and use it to compile CoffeeScript files to JavaScript for use in projects.
Apresentação em português dos motivos para escolher ScalaFX para criar aplicativos nativos para as plataformas Mac OS X, Linux e Windows. Explico em português minha caminhada atrás das alternativas no mundo do JavaFX2 após a retirada do JavaFX Script em setembro de 2010. Descubra aqui por que eu fiquei com ScalaFX como alternativa mais elegante e fácil de programar.
The document discusses Scala and how it compares to Java 8 features. It covers Scala's support for lambda expressions, parallel collections, default interface implementations, and its earlier delivery date compared to Java 8. Code samples in both Java 8 and Scala are shown to demonstrate these features. The document encourages learning Scala and provides a code sample and link to more examples.
Code for Startup MVP (Ruby on Rails) Session 2Henry S
This document provides an overview and agenda for a workshop on learning to code for startup MVPs using Ruby on Rails. It covers setting up the development environment, a review of concepts from the previous session, and a focus on Ruby basics, Rails models, and using Devise for user authentication.
The document discusses CoffeeScript, a programming language that compiles to JavaScript. It was designed to have cleaner syntax than JavaScript and be easier to read and write. CoffeeScript code compiles directly to equivalent JavaScript code. Using CoffeeScript can help developers write less code that is more readable and maintainable while still being able to use existing JavaScript libraries. The document provides examples of CoffeeScript code and the equivalent JavaScript output. It also discusses how to use CoffeeScript with Ruby on Rails projects by adding the Barista gem.
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012Amazon Web Services
Learn how to work with Amazon DynamoDB using the AWS SDK for PHP. Attendees learn about the AWS SDK for PHP including how to install and configure the SDK and how to perform operations with DynamoDB. Advanced discussion topics include tips for effective DynamoDB usage, request batching, performance tuning, configuring event listeners, and setting up the included DynamoDB session handler for session storage.
The AWS Command Line Interface (AWS CLI) provides an easy-to-use command line interface to AWS and allows you to create powerful automation scripts. In this session, you learn advanced techniques that open up new scenarios for using the AWS CLI. We demonstrate how to filter and transform service responses and how to chain and script commands, and we explore new features in the AWS CLI.
This document summarizes new features and improvements planned for the Gatling load testing tool. Key points include:
- Adopting an actor model to represent scenario workflows as sequences of asynchronous actors.
- Refactoring the expression language to type check values and return failures instead of exceptions.
- Improving resource fetching to better approximate how browsers parallelize asset loading instead of sequential requests.
- Enhancing checks like regular expressions to support returning tuples instead of just strings.
- Simplifying templating to use string interpolation and external template files with expression language instead of Scalate.
This document provides an introduction to Swift 2 and covers various Swift language basics including variables and constants, arrays, optionals, functions and closures, classes, structs, enums, protocols, and generics. It discusses syntax, properties, methods and gives examples for each language feature. The document is organized into sections for each language concept and provides code samples and explanations.
Objective-C runtime is a foundation for the awesomeness all iOS and Mac OS X developers love. We'll take a look at the core pieces that make the runtime dynamism possible
The document discusses the AddressBook framework in Swift, including ABAddressBookRef which represents an address book, ABRecordRef which represents a person, group or source, and ABMulitValueRef which represents a multi-valued property like multiple phone numbers. It provides code examples for creating and accessing these objects to retrieve and work with contact data from the address book.
The document discusses JavaScript, describing it as:
- Created in 1995 by Netscape and based on the ECMAScript standard.
- A dynamic, weakly typed, object-oriented programming language that is often misunderstood.
- Used for client-side scripting of webpages as well as server-side and application scripting.
- Commonly disliked due to past bad practices, implementations, and browser differences, but these issues are improving over time.
The document discusses how to work with Cocoa and Objective-C from Swift. It covers importing Objective-C frameworks, interacting with Objective-C APIs such as initializers, properties, and methods, type remapping between Objective-C and Swift types, working with AnyObject and optionals, blocks, and integrating Swift code with Interface Builder using outlets and actions.
Ensuring software reliability, resiliency, and recoverability is best achieved by practicing effective defensive coding. Take a crash course in defensive coding with PHP and learn about attack surfaces, input validation, canonicalization, secure type checking, external library vetting, cryptographic agility, exception management, code reviews, and unit and behavioral testing. Learn some helpful tips and tricks from experienced professionals within the PHP community as we review the latest blogs and discussions on best practices to defend your project.
Taskulu helps teams collaborate and communicate online by providing task management and live chat features that teams can customize. Ruby on Rails is an open-source web application framework that favors convention over configuration for programmer happiness and sustainable productivity. It uses the model-view-controller architectural pattern and includes generators, models, controllers, views and other components that help enable rapid development according to conventions.
The document summarizes Carlo Sciolla's blog post about using Clojure to interact with the Alfresco content repository. It shows how to write a function in Clojure to loop through all nodes in a repository and print their names, and compares the Clojure code to the equivalent Java code. It also discusses some Clojure concepts like immutable data structures, macros, and sequence processing that make the Clojure implementation more concise and functional than the object-oriented Java code.
This document discusses using Clojure to interact with the Alfresco content management system. It provides an example of using Clojure to loop through all nodes in the Alfresco repository and print their names. It then explores translating the Java code into an idiomatic Clojure implementation using features like macros, immutable data structures, and Clojure's powerful seq library for processing sequences. The document aims to illustrate how a functional programming language like Clojure can provide benefits for working with Alfresco.
Rami Sayar presented on ECMAScript 6 (ES6) features including block scoping with let and const, destructuring, modules and classes, and iterators and generators. ES6 is targeted for ratification in mid-2015 and brings significant updates to JavaScript. Browser and Node.js support is emerging for ES6 features through experimental flags or transpilation to ES5.
An Introduction to core ideas, characteristics and benefits of functional programming and their implementation within the so called ‘object – functional’ language Scala.
Leaving the widely known concepts of object oriented programming aside, the focus is directed on how to leverage Scala in order to perform the following topics (extract):
* Functions and Function types
* Lambdas and Closures
* Currying and partial Argument Application
* Algebraic datatypes and Pattern matching
* Higher Order Functions
* Composition and Combinators
This document summarizes Mario Gleichmann's presentation on functional Scala to a Java user group in Frankfurt. It discusses functional programming concepts like functions as first-class values, higher-order functions, currying, partial application, and function composition using combinators. It provides examples of extracting prime numbers from a list and managing database resources functionally. The document concludes with an example problem of counting even words in a sentence.
CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar that makes JavaScript cleaner and adds features inspired by Python and Ruby. Key features include cleaner syntax for functions, objects, conditionals, loops, and classes. CoffeeScript code compiles directly to equivalent JavaScript code, so it can be used anywhere JavaScript is used like web browsers and Node.js. To use CoffeeScript, install the CoffeeScript compiler and use it to compile CoffeeScript files to JavaScript for use in projects.
Apresentação em português dos motivos para escolher ScalaFX para criar aplicativos nativos para as plataformas Mac OS X, Linux e Windows. Explico em português minha caminhada atrás das alternativas no mundo do JavaFX2 após a retirada do JavaFX Script em setembro de 2010. Descubra aqui por que eu fiquei com ScalaFX como alternativa mais elegante e fácil de programar.
The document discusses Scala and how it compares to Java 8 features. It covers Scala's support for lambda expressions, parallel collections, default interface implementations, and its earlier delivery date compared to Java 8. Code samples in both Java 8 and Scala are shown to demonstrate these features. The document encourages learning Scala and provides a code sample and link to more examples.
Code for Startup MVP (Ruby on Rails) Session 2Henry S
This document provides an overview and agenda for a workshop on learning to code for startup MVPs using Ruby on Rails. It covers setting up the development environment, a review of concepts from the previous session, and a focus on Ruby basics, Rails models, and using Devise for user authentication.
The document discusses CoffeeScript, a programming language that compiles to JavaScript. It was designed to have cleaner syntax than JavaScript and be easier to read and write. CoffeeScript code compiles directly to equivalent JavaScript code. Using CoffeeScript can help developers write less code that is more readable and maintainable while still being able to use existing JavaScript libraries. The document provides examples of CoffeeScript code and the equivalent JavaScript output. It also discusses how to use CoffeeScript with Ruby on Rails projects by adding the Barista gem.
TLS305 Using DynamoDB with the AWS SDK for PHP - AWS re: Invent 2012Amazon Web Services
Learn how to work with Amazon DynamoDB using the AWS SDK for PHP. Attendees learn about the AWS SDK for PHP including how to install and configure the SDK and how to perform operations with DynamoDB. Advanced discussion topics include tips for effective DynamoDB usage, request batching, performance tuning, configuring event listeners, and setting up the included DynamoDB session handler for session storage.
The AWS Command Line Interface (AWS CLI) provides an easy-to-use command line interface to AWS and allows you to create powerful automation scripts. In this session, you learn advanced techniques that open up new scenarios for using the AWS CLI. We demonstrate how to filter and transform service responses and how to chain and script commands, and we explore new features in the AWS CLI.
This document summarizes new features and improvements planned for the Gatling load testing tool. Key points include:
- Adopting an actor model to represent scenario workflows as sequences of asynchronous actors.
- Refactoring the expression language to type check values and return failures instead of exceptions.
- Improving resource fetching to better approximate how browsers parallelize asset loading instead of sequential requests.
- Enhancing checks like regular expressions to support returning tuples instead of just strings.
- Simplifying templating to use string interpolation and external template files with expression language instead of Scalate.
This document provides an introduction to Swift 2 and covers various Swift language basics including variables and constants, arrays, optionals, functions and closures, classes, structs, enums, protocols, and generics. It discusses syntax, properties, methods and gives examples for each language feature. The document is organized into sections for each language concept and provides code samples and explanations.
Objective-C runtime is a foundation for the awesomeness all iOS and Mac OS X developers love. We'll take a look at the core pieces that make the runtime dynamism possible
The document discusses the AddressBook framework in Swift, including ABAddressBookRef which represents an address book, ABRecordRef which represents a person, group or source, and ABMulitValueRef which represents a multi-valued property like multiple phone numbers. It provides code examples for creating and accessing these objects to retrieve and work with contact data from the address book.
The document discusses JavaScript, describing it as:
- Created in 1995 by Netscape and based on the ECMAScript standard.
- A dynamic, weakly typed, object-oriented programming language that is often misunderstood.
- Used for client-side scripting of webpages as well as server-side and application scripting.
- Commonly disliked due to past bad practices, implementations, and browser differences, but these issues are improving over time.
The document discusses how to work with Cocoa and Objective-C from Swift. It covers importing Objective-C frameworks, interacting with Objective-C APIs such as initializers, properties, and methods, type remapping between Objective-C and Swift types, working with AnyObject and optionals, blocks, and integrating Swift code with Interface Builder using outlets and actions.
Ensuring software reliability, resiliency, and recoverability is best achieved by practicing effective defensive coding. Take a crash course in defensive coding with PHP and learn about attack surfaces, input validation, canonicalization, secure type checking, external library vetting, cryptographic agility, exception management, code reviews, and unit and behavioral testing. Learn some helpful tips and tricks from experienced professionals within the PHP community as we review the latest blogs and discussions on best practices to defend your project.
Taskulu helps teams collaborate and communicate online by providing task management and live chat features that teams can customize. Ruby on Rails is an open-source web application framework that favors convention over configuration for programmer happiness and sustainable productivity. It uses the model-view-controller architectural pattern and includes generators, models, controllers, views and other components that help enable rapid development according to conventions.
The document summarizes Carlo Sciolla's blog post about using Clojure to interact with the Alfresco content repository. It shows how to write a function in Clojure to loop through all nodes in a repository and print their names, and compares the Clojure code to the equivalent Java code. It also discusses some Clojure concepts like immutable data structures, macros, and sequence processing that make the Clojure implementation more concise and functional than the object-oriented Java code.
This document discusses using Clojure to interact with the Alfresco content management system. It provides an example of using Clojure to loop through all nodes in the Alfresco repository and print their names. It then explores translating the Java code into an idiomatic Clojure implementation using features like macros, immutable data structures, and Clojure's powerful seq library for processing sequences. The document aims to illustrate how a functional programming language like Clojure can provide benefits for working with Alfresco.
Rami Sayar presented on ECMAScript 6 (ES6) features including block scoping with let and const, destructuring, modules and classes, and iterators and generators. ES6 is targeted for ratification in mid-2015 and brings significant updates to JavaScript. Browser and Node.js support is emerging for ES6 features through experimental flags or transpilation to ES5.
An Introduction to core ideas, characteristics and benefits of functional programming and their implementation within the so called ‘object – functional’ language Scala.
Leaving the widely known concepts of object oriented programming aside, the focus is directed on how to leverage Scala in order to perform the following topics (extract):
* Functions and Function types
* Lambdas and Closures
* Currying and partial Argument Application
* Algebraic datatypes and Pattern matching
* Higher Order Functions
* Composition and Combinators
This document summarizes Mario Gleichmann's presentation on functional Scala to a Java user group in Frankfurt. It discusses functional programming concepts like functions as first-class values, higher-order functions, currying, partial application, and function composition using combinators. It provides examples of extracting prime numbers from a list and managing database resources functionally. The document concludes with an example problem of counting even words in a sentence.
What's new with Scala 2.10.0? A brief look at the past, and a detailed look at what's coming down the pipeline.
Note: at the time this presentation was created, Scala 2.10.0 had not been released yet. The final version will probably differ in some ways.
Last update: September 20th
Scala for Java Developers (Silicon Valley Code Camp 13)Ramnivas Laddad
My presentation at Silicon Valley Code Camp 13 (http://www.siliconvalley-codecamp.com/Session/2013/scala-for-java-developers). The target audience is Java developers who wants to get started with Scala.
This presentation is based on Joakim\’s experiences from moving from Java to Scala http://www.scala-lang.org/node/960#Joak We will explore how to move from Java to Scala and why. We\’ll look at things that you will run into sooner rather than later such as Scala\’s collection APIs, Options and higher order functions and special syntax. You will leave this presentation with good foundation to use Scala in practice; perhaps even in your current Java project and ideally with an appetite to learn more.
Big Data - Gold panning in the information ageClueda AG
The document discusses big data and how companies can extract value from large amounts of unstructured data using cognitive computing. It describes Clueda, a company that provides real-time analysis of unstructured information like news, blogs, tweets and emails to detect events and trends. Clueda's technology can process 1,000 sentences per second and generate alerts, helping clients make faster decisions than competitors. The document outlines potential applications in areas like portfolio monitoring and compliance.
Social Data: technische Herausforderungen, rechtliche Hürden und wirtschaftli...Clueda AG
Jeder spricht darüber, alle wollen Daten, Daten, Daten. Unmengen unstrukturierter Daten sammeln sich dann auf dem Server. Aber was kann und darf ich damit überhaupt machen? Ergiebige Quelle von Big Data sind Social-Media-Kanäle wie Facebook. Social Data lässt sich beispielsweise für das Lead Scoring, Customer-Insights-Analysen und automatisierte Produktempfehlungen nutzen. Welche technischen und rechtlichen Hürden dabei zu nehmen sind und welche Chancen sich für Unternehmen bieten, wird anhand ausgewählte Fallbeispiele gezeigt.
Clueda - Baader Investment Conference 2014Clueda AG
The document discusses big data applications in portfolio monitoring, risk management, and compliance for financial services. It describes how real-time analysis of structured and unstructured data can provide alerts and insights to support faster decision-making. Example applications discussed include monitoring over a million financial instruments and news items to detect market movements, and analyzing communications to ensure regulatory compliance.
The workshop aims to introduce Scala > 2.10 and was held at Clueda AG .
It gives an introduction to Scala also explaining widely used language features like case classes, patten matching, futures and string interpolation.
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
Scala is a modern multi-paradigm programming language that integrates features of object-oriented and functional programming. It is statically typed, has a lightweight syntax, and compiles to Java bytecode so it can use Java libraries. Scala source code is compiled to Java bytecode using the Scala compiler and runs on the Java Virtual Machine. Common data structures in Scala include collections like lists, arrays, sets and maps. Scala supports higher-order functions, immutable data, pattern matching and case classes. Build tools like SBT are used to manage Scala projects.
This document provides an introduction and overview of the Scala programming language. It begins with a brief history of Scala's creation at EPFL by Martin Odersky in 2001. It then discusses some of the key reasons for using Scala, including its ability to scale with demands through a combination of object-oriented and functional programming concepts. The document outlines some of Scala's main features, such as its static typing, interoperability with Java, and support for modularity. It also provides examples of Scala's data types, operations, control structures, functions, and pattern matching capabilities. Overall, the summary provides a high-level introduction to Scala's origins, design philosophy, and programming paradigms.
This document discusses TypeScript, a superset of JavaScript that adds optional static typing and class-based object-oriented programming. It allows developers to gradually introduce typing into JavaScript code for improved productivity and catch errors early. The document covers TypeScript features like interfaces, classes, modules, type definitions, and comparisons to alternatives like CoffeeScript and Dart. It concludes that TypeScript allows gradual adoption of typing while following the future ECMAScript standard.
The document provides an introduction and overview of the Scala programming language presented by Prasanna Kumar at a JUG-C group meetup. It covers topics such as what Scala is, why use Scala, basics of Scala programming constructs, development environments, frameworks, and learning resources.
Scala can be used for both object-oriented programming and functional programming. It supports features like functions as first-class objects, closures, patterns, and immutable data structures. Scala can be used to build domain specific languages through its support for features like functions, pattern matching, and implicit conversions. Some examples of Scala DSLs include SimpleModeler for modeling and g3/g4 for Android development. Scala also supports concepts from functional programming like functors, monads, and other type classes to build abstractions.
This document provides an introduction to the Scala programming language. It discusses that Scala was created by Martin Odersky in 2003 as a hybrid functional and object-oriented language that runs on the Java Virtual Machine. Some key points made include that Scala code compiles to Java bytecode, allows importing of Java libraries, and supports features like functions as first-class objects. The document also provides examples of Hello World programs in Scala and Java for comparison, and demonstrates basic Scala concepts like variables, conditionals, loops, and lists.
Scalding - the not-so-basics @ ScalaDays 2014Konrad Malawski
This document discusses various big data technologies and how they relate to each other. It explains that Summingbird is built on top of Scalding and Storm, which are built on top of Cascading, which is built on top of Hadoop. It also discusses how Spark relates and compares to these other technologies.
This document provides an agenda and notes for a talk on optimizing Scala code to solve real-world problems without explosions, broken thumbs, or bullet wounds. The agenda includes discussing mantras, collection functions, implicits, and style. It emphasizes writing expressions instead of statements, avoiding null, staying immutable, using options instead of null checks, and limiting the scope of implicits. It also covers collection functions, type classes, and breaking out of for-comprehensions. The overall message is to write clear, concise Scala code using best practices around expressions, immutability, and type safety.
Qcon2011 functions rockpresentation_scalaMichael Stal
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.
Solid and Sustainable Development in Scalascalaconfjp
Kazuhiro Sera introduced several of his Scala projects including ScalikeJDBC, Skinny Framework, and AWScala. He discussed some of his philosophies for solid and sustainable development in Scala including using simplified class-based OOP with immutable data structures, avoiding overkill abstraction, writing tests without question, keeping infrastructure lightweight, and ensuring projects have no surprises for newcomers. He welcomed questions during the upcoming AMA session.
The document provides an overview of the Scala programming language. It begins with an agenda that outlines topics like differences between Java and Scala, Scala data types, variables, classes, functions, closures, exception handling and collections. It then discusses specific aspects of Scala like verbosity reduction compared to Java, functional programming influences, object-oriented features, interoperability with Java and compilation to Java bytecode. Examples are provided to illustrate Scala concepts like functions, classes, recursion, higher-order functions and exception handling. The document aims to explain Scala and reasons for differences from Java.
This document provides an overview of the Scala programming language. Scala was designed to be scalable by unifying object-oriented and functional programming. It runs on the Java Virtual Machine and interoperates with Java libraries. Scala code is more concise than Java due to features like type inference, immutable data structures, and support for functional programming patterns. Popular frameworks developed using Scala include Apache Spark, Kafka, and Akka. Scala sees widespread use in domains like big data, web development, and scientific computing.
- Scala originated from Martin Odersky's work on functional programming languages like OCaml in the 1980s and 1990s. It was designed to combine object-oriented and functional programming in a practical way.
- Key aspects of Scala include being statically typed while also being flexible, its unified object and module system, and treating libraries as primary over language features.
- Scala has grown into an large ecosystem centered around the JVM and also targets JavaScript via Scala.js. Tooling continues to improve with faster compilers and new IDE support.
- Future work includes establishing TASTY as a portable intermediate representation, connecting Scala to formal foundations through the DOT calculus, and exploring new type
My talk at Bangalore Java Users Group. It was meant developers who want to get them started on Scala. This talk objectives was to get started on creating a project in Scala, write some code using collections and test it using ScalaTest.
Slides from my talk at the Feb 2011 Seattle Tech Startups meeting. More info here (along with powerpoint slides): http://www.startupmonkeys.com/2011/02/scala-frugal-mechanic/
This document provides an overview of Scala-ActiveRecord, a type-safe Active Record model library for Scala. It discusses features such as being type-safe, having Rails ActiveRecord-like functionality, automatic transaction control, and support for associations and validations. The document also covers getting started, defining schemas, CRUD operations, queries, caching queries, validations, callbacks, and relationships.
TDC 2012 - Patterns e Anti-Patterns em RubyFabio Akita
Palestra apresentada no The Developers Conference 2012 em São Paulo. Explicação sobre Patterns e Anti-Patterns em Ruby para quem está iniciando a aprender a linguagem.
Scala provides a more concise and flexible syntax compared to Java. It includes pre-built libraries that make programming easier. Scala supports native XML processing and allows parsing real-world data. An example shows how a simple "Hello World" program requires less code and boilerplate in Scala versus Java due to features like not needing a main method or importing output streams. Scala also provides more functional capabilities than Java like mapping lists to extract subsets in a simpler way using functions like flatMap. Classes can also be extended from functions, showing Scala's flexibility in mixing object-oriented and functional paradigms.
Analysis insight about a Flyball dog competition team's performanceroli9797
Insight of my analysis about a Flyball dog competition team's last year performance. Find more: https://github.com/rolandnagy-ds/flyball_race_analysis/tree/main
Global Situational Awareness of A.I. and where its headedvikram sood
You can see the future first in San Francisco.
Over the past year, the talk of the town has shifted from $10 billion compute clusters to $100 billion clusters to trillion-dollar clusters. Every six months another zero is added to the boardroom plans. Behind the scenes, there’s a fierce scramble to secure every power contract still available for the rest of the decade, every voltage transformer that can possibly be procured. American big business is gearing up to pour trillions of dollars into a long-unseen mobilization of American industrial might. By the end of the decade, American electricity production will have grown tens of percent; from the shale fields of Pennsylvania to the solar farms of Nevada, hundreds of millions of GPUs will hum.
The AGI race has begun. We are building machines that can think and reason. By 2025/26, these machines will outpace college graduates. By the end of the decade, they will be smarter than you or I; we will have superintelligence, in the true sense of the word. Along the way, national security forces not seen in half a century will be un-leashed, and before long, The Project will be on. If we’re lucky, we’ll be in an all-out race with the CCP; if we’re unlucky, an all-out war.
Everyone is now talking about AI, but few have the faintest glimmer of what is about to hit them. Nvidia analysts still think 2024 might be close to the peak. Mainstream pundits are stuck on the wilful blindness of “it’s just predicting the next word”. They see only hype and business-as-usual; at most they entertain another internet-scale technological change.
Before long, the world will wake up. But right now, there are perhaps a few hundred people, most of them in San Francisco and the AI labs, that have situational awareness. Through whatever peculiar forces of fate, I have found myself amongst them. A few years ago, these people were derided as crazy—but they trusted the trendlines, which allowed them to correctly predict the AI advances of the past few years. Whether these people are also right about the next few years remains to be seen. But these are very smart people—the smartest people I have ever met—and they are the ones building this technology. Perhaps they will be an odd footnote in history, or perhaps they will go down in history like Szilard and Oppenheimer and Teller. If they are seeing the future even close to correctly, we are in for a wild ride.
Let me tell you what we see.
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...sameer shah
"Join us for STATATHON, a dynamic 2-day event dedicated to exploring statistical knowledge and its real-world applications. From theory to practice, participants engage in intensive learning sessions, workshops, and challenges, fostering a deeper understanding of statistical methodologies and their significance in various fields."
The Ipsos - AI - Monitor 2024 Report.pdfSocial Samosa
According to Ipsos AI Monitor's 2024 report, 65% Indians said that products and services using AI have profoundly changed their daily life in the past 3-5 years.
ViewShift: Hassle-free Dynamic Policy Enforcement for Every Data LakeWalaa Eldin Moustafa
Dynamic policy enforcement is becoming an increasingly important topic in today’s world where data privacy and compliance is a top priority for companies, individuals, and regulators alike. In these slides, we discuss how LinkedIn implements a powerful dynamic policy enforcement engine, called ViewShift, and integrates it within its data lake. We show the query engine architecture and how catalog implementations can automatically route table resolutions to compliance-enforcing SQL views. Such views have a set of very interesting properties: (1) They are auto-generated from declarative data annotations. (2) They respect user-level consent and preferences (3) They are context-aware, encoding a different set of transformations for different use cases (4) They are portable; while the SQL logic is only implemented in one SQL dialect, it is accessible in all engines.
#SQL #Views #Privacy #Compliance #DataLake
Learn SQL from basic queries to Advance queriesmanishkhaire30
Dive into the world of data analysis with our comprehensive guide on mastering SQL! This presentation offers a practical approach to learning SQL, focusing on real-world applications and hands-on practice. Whether you're a beginner or looking to sharpen your skills, this guide provides the tools you need to extract, analyze, and interpret data effectively.
Key Highlights:
Foundations of SQL: Understand the basics of SQL, including data retrieval, filtering, and aggregation.
Advanced Queries: Learn to craft complex queries to uncover deep insights from your data.
Data Trends and Patterns: Discover how to identify and interpret trends and patterns in your datasets.
Practical Examples: Follow step-by-step examples to apply SQL techniques in real-world scenarios.
Actionable Insights: Gain the skills to derive actionable insights that drive informed decision-making.
Join us on this journey to enhance your data analysis capabilities and unlock the full potential of SQL. Perfect for data enthusiasts, analysts, and anyone eager to harness the power of data!
#DataAnalysis #SQL #LearningSQL #DataInsights #DataScience #Analytics
Codeless Generative AI Pipelines
(GenAI with Milvus)
https://ml.dssconf.pl/user.html#!/lecture/DSSML24-041a/rate
Discover the potential of real-time streaming in the context of GenAI as we delve into the intricacies of Apache NiFi and its capabilities. Learn how this tool can significantly simplify the data engineering workflow for GenAI applications, allowing you to focus on the creative aspects rather than the technical complexities. I will guide you through practical examples and use cases, showing the impact of automation on prompt building. From data ingestion to transformation and delivery, witness how Apache NiFi streamlines the entire pipeline, ensuring a smooth and hassle-free experience.
Timothy Spann
https://www.youtube.com/@FLaNK-Stack
https://medium.com/@tspann
https://www.datainmotion.dev/
milvus, unstructured data, vector database, zilliz, cloud, vectors, python, deep learning, generative ai, genai, nifi, kafka, flink, streaming, iot, edge
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...Aggregage
This webinar will explore cutting-edge, less familiar but powerful experimentation methodologies which address well-known limitations of standard A/B Testing. Designed for data and product leaders, this session aims to inspire the embrace of innovative approaches and provide insights into the frontiers of experimentation!
The Building Blocks of QuestDB, a Time Series Databasejavier ramirez
Talk Delivered at Valencia Codes Meetup 2024-06.
Traditionally, databases have treated timestamps just as another data type. However, when performing real-time analytics, timestamps should be first class citizens and we need rich time semantics to get the most out of our data. We also need to deal with ever growing datasets while keeping performant, which is as fun as it sounds.
It is no wonder time-series databases are now more popular than ever before. Join me in this session to learn about the internal architecture and building blocks of QuestDB, an open source time-series database designed for speed. We will also review a history of some of the changes we have gone over the past two years to deal with late and unordered data, non-blocking writes, read-replicas, or faster batch ingestion.
1. An Introduction to Scala
Andreas Neumann,
Senior Software Engineer!
a.neumann@clueda.com
2. Overview
⬤A very short history of Scala!
⬤Using Scala - Basics: Compile and run!
⬤Introduction to the core concepts : vals, classes, objects, traits, control
structures and functions!
⬤Some intermediate concepts in Scala: Pattern Matching, Option, XML, Futures!
⬤Patterns in Scala!
⬤Functional Style
Clueda AG
2
3. About Scala
⬤A JVM Languge!
⬤multiparadigmatic!
⬤functional object orientated
Clueda AG
3
4. The father of Scala - Martin Odersky
⬤Professor EPFL!
⬤Java-Compiler!
⬤Java 1.4 Generics!
⬤PIZZA!
⬤Scala!
⬤Co-Founder Typesafe
Clueda AG
4
5. The company behind Scala -
⬤Training!
⬤Consulting!
⬤Scala!
⬤Actor!
⬤Play
Clueda AG
5
6. Who is using Scala
⬤Xerox!
⬤Twitter!
⬤Foursquare!
⬤Sony!
⬤Siemens!
⬤clueda!
⬤…
Clueda AG
6
7. Nice features
⬤Can be integrated in any Java based architecture!
⬤support concurrent and asynchronous operations out of the box in many
flavors (Futures,Parallel Collections, Akka)!
⬤great for embedded DSLs
Clueda AG
7
8. Introduction
⬤Run code / compile Code!
⬤Syntax (some tips)!
⬤declare variables!
⬤functions!
⬤clases, traits and objects
Clueda AG
8
9. Run code, compile sources
⬤Scala can be used in many different environments:!
⬤compile and run on a JVM!
⬤run as a script!
⬤in an interactive console, called REPL
Clueda AG
9
10. Scala - compiler / scalac
⬤the compiler is called scalac!
⬤The sources are compiled to
Java byte code!
⬤*.class!
⬤run class with scala <name>
Clueda AG
10
11. Scripting with Scala - Unix
⬤Scala can be used as scripting language!
⬤change mode to executeable or run by bash
Clueda AG
11
#!/bin/sh
exec scala "$0" "$@"
!#
!
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world! " +
args.toList)
}
}
HelloWorld.main(args)
12. Scripting with Scala - Windows
⬤Resembles UNIX use a batch script instead!
⬤*.bat!
⬤run
Clueda AG
12
::#!!
@echo off!
call scala %0 %*!
goto :eof!
::!#! !
object HelloWorld {!
def main(args: Array[String]) {!
println("Hello, world! " +!
args.toList)!
}!
}!
!
HelloWorld.main(args)
13. Scala - Interpreter / REPL
⬤part of the scala installation!
⬤Start by typing scala the shell!
⬤:q or CTRL + d to quit
Clueda AG
13
neumann@mac ~> scala!
!!
Welcome to Scala version 2.11.1 (Java HotSpot(TM) !
64-Bit Server VM, Java 1.7.0_55).!
Type in expressions to have them evaluated.!
Type :help for more information.!
!
scala> println("Hello World")!
Hello World!
!
scala> :q!
!!
neumann@mac ~>
15. Syntax
⬤No need for „;“ , one expression per line !
⬤Still possible to add ; if for example you want several expression within one line!
⬤The dot on method invocations can be dropped. It is best practice to do so with
infix invocation but not with postfix operations.
Clueda AG
15
"Hallo Welt !".split(" ")!
//res0: Array[String] = Array(Hallo, Welt, !)! !
scala> "Hallo Welt !" split " " !
//res2: Array[String] = Array(Hallo, Welt, !)
scala> List(1,2.3).map(_ * 3).head!
//res3: Double = 3.0! !
scala> ( List(1,2.3) map (_ * 3) ).head!
//res4: Double = 3.0
16. val, vars
⬤val creates a Value which is not changeable ( like final modifier in Java)!
⬤var creates a Variable , which can be reassigned different values
Clueda AG
16
17. Example: val and var
Clueda AG
17
val x = 42!
//x: Int = 42!
!
var y = 99!
//y: Int = 99!
!
y = 1!
y: Int = 1!
!
x = 1!
error: reassignment to val!
x = 1!
^
18. Types and type inferrence
⬤Types are introduced after : which is written behind the var/val!
!
⬤Giving the type explicitly is optional as the type inference can infer the type. It’s
considered good style to add the type information nonetheless.
Clueda AG
18
s : String = "ein String"
val a = "Hallo"!
//a: java.lang.String = Hallo!
!
val b = 1!
//b: Int = 1!
!
val c = 3.5!
//c: Double = 3.5!
!
val d = List(1,2.0)!
//d: List[Double] = List(1.0, 2.0)
19. define methods
⬤methods are introduced with def!
⬤optionally there can be a list of
parameters enclosed by parentheses!
⬤then the body of the function!
⬤methods returning a value put a
between name arguments and the
body!
⬤the result of the last expression
evaluated within the body is the
return value
Clueda AG
19
def write(aString: String):Unit=
{!
println(aString) !
}!
!
write("Hallo ihr alle da
draußen!")!
//Hallo ihr alle da draußen!
def add(x: Int, y:Int) : Int = { !
x + y!
}!
!
add(40,2)!
//res0: Int = 42
20. Collections
⬤Scala has a big Collections library!
⬤Collections provide similar interfaces as far as possible!
⬤Most collections come in up to four flavors:!
⬤basic (mostly = immutable)!
⬤immutable!
⬤mutable!
⬤parallel
Clueda AG
20
26. Classes
⬤Classes are introduced by the keyword class !
⬤Optionally each class has constructor elements in parentheses!
⬤optionally there is a class body!
⬤Things to look out for!
⬤Constructor elements prepended with the keyword val automatically get a
getter method with the same name as the val (uniform access principle)!
⬤Constructor elements prepended with the keyword var get a getter method
and a setter method with the same name as the var (uniform access
principle)!
⬤Every expression within the body gets evaluated and called on object
creation time
Clueda AG
26
27. Example: A scala class
⬤Instances are created with new <ClassName>
Clueda AG
27
class Document(val title: String, val author: String, yearInt: Int) {!
!
val year = yearInt.toString!
!
def shortCitation: String = author + " : " + title + ". " + year!
}!
!
val scalaBook = !
! new Document("Programming In Scala","Martin Odersky",2011)!
!
println(scalaBook.title)!
println(scalaBook.year)!
28. Scala Objects
⬤Objects are created using the keyword object!
⬤They have NO constructor!
⬤Works roughly like a java class with static methods!
⬤Calling members ObjectName.member or ObjectName.method!
⬤Singleton-Object
Clueda AG
28
29. Scala Object - Example
Clueda AG
29
object DeepThought {!
!
! val theMeaningOfLife =!
"The meaning of life: 42"!
!
! def speak {!
println(theMeaningOfLife)!
}!
!
}!
!
DeepThought.speak!
//The meaning of life: 42
30. Companion Object
⬤Widely used pattern in Scala!
⬤A object with the same name as a class!
⬤Native Constructor Pattern
Clueda AG
30
31. Case Class
⬤Introduce using the keywords case class!
⬤Like a „normal class“!
⬤Defines a companion object automatically with apply, unapply and some other
methods!
⬤All constructor elements have getter methods as if prepended by val!
⬤Adds hashCode and equals based on the constructor Elements!
⬤Other classes must not inherit from case classes
Clueda AG
31
32. Case Class - Example
Clueda AG
32
case class Book(title: String, pages :Int)!
//defined class Book!
!
val book = Book("Necronomicon",1000)!
//book: Book = Book(Necronomicon,1000)!
!
println( book.title )!
//Necronomicon!
!
book == Book("Necronomicon",1000)!
//Boolean = true!
!
scala> book.hashCode!
//-364191203!
!
scala> Book("Necronomicon",1000).hashCode!
//-364191203
33. Trait
⬤introduced with keyword trait!
⬤roughly comparable to a java interface!
⬤allows an effect resembling multiple inheritance without the dangers (i.e.
diamond of death)!
⬤small building blocks!
⬤like ruby mixins
Clueda AG
33
34. Trait - Example
⬤Two „traits“ are defined as
Traits: Edible and ExoticTaste!
⬤Two classes are defined:
Cake, which implements
edible and ChiliChoc
implements Edible and
ExoticTaste
Clueda AG
34
!!
trait Edible {!
! def taste: String!
! def eat = println(taste)!
}!
! trait ExoticTaste {!
! def eat: Unit! def describeTaste = {!
! ! eat!
! ! println("It tastes exotic")!
! }!
}! !!
case class Cake() extends Edible {!
! def taste = "sweet"!
}! !
case class ChilliChoc(taste: String) !
! ! ! ! ! ! extends Edible with
ExoticTaste
35. Trait - Example : Usage
Clueda AG
35
val cake = new Cake()!
cake.eat! !
val chilliChoc = ChilliChoc("sweet and hot")! !
chilliChoc.eat!
chilliChoc.describeTaste
scala> val cake = new Cake()!
cake: Cake = Cake()! !
scala> cake.eat!
sweet! !!
scala> val chilliChoc = ChilliChoc("sweet and hot")!
chilliChoc: ChilliChoc = ChilliChoc(sweet and hot)! !
scala> chilliChoc.eat!
sweet and hot! !
scala> chilliChoc.describeTaste!
sweet and hot!
It tastes exotic
37. Control structures
⬤Control structures like while, if and else work as in Java or C!
⬤In contrast to Java, control structures are functions, i.e. they return a value!
⬤while always returns returns Unit
Clueda AG
37
val x = if ( 1 < 2 ) true!
//x: AnyVal = true
38. functional control structures
⬤some Examples!
⬤map : Apply function to each given element , keep result (like looping and
collecting the results)!
!
!
⬤foreach: Apply function to each given element , drop result
Clueda AG
38
List(1,2,3,4) map (x => x + 1)!
//res1: List[Int] = List(2, 3, 4, 5)
List(1,2,3) foreach ( x => println(s"And a $x") )!
!
//And a 1!
//And a 2!
//And a 3
39. matching
⬤Pattern matching!
⬤keyword match!
⬤A group of cases introduced with the keyword case !
⬤Switch on Steroids!
⬤Pattern Guards allow better control flow!
⬤Case Classes and Extractor Patterns for easy deconstruction and
extraction of input
Clueda AG
39
40. Matching Example
Clueda AG
40
books: List[Any] = !
List(Book(Programming Scala,883,2012),
Book(Programming Pearl,1104,2000), Book(Necronomicon,
666,666), Ein String, 5, 42)! !b
ookComments: List[String] = !
List(New Scala Book by Martin Odersky from 2012,
Programming Pearl 1104 2000, Necronomicon 666 666,
Something else, Something else, an integer bigger than 10)!
case class Book( title: String, pages: Int, year:
Int)! !
val books = List( !
! Book("Programming Scala", 883, 2012),!
! Book("Programming Pearl", 1104, 2000),!
! Book("Necronomicon",666,666),!
! "Ein String“, 5, 42!
)! !
val bookComments = books map {!
! case Book("Programming Scala", pages, year)
=> !
! ! s"New Scala Book by Martin Odersky
from $year"!
! case Book(title, pages,year) => !
! ! s"$title $pages $year"!
! case x: Int if x > 10 => !
! ! "an integer bigger than 10"!
! case _ => !
! ! "Something else"!
}
41. For-Comprehensions
⬤program with a DSL that looks a lot like pseudocode!
⬤will be translated to map, filter, flatMap and reduce operations by the compiler
Clueda AG
41
def isEven(x: Int) = x % 2 == 0!
val integers = for {!
x <- 1 to 99!
if isEven(x)!
if x % 5 == 0!
} yield x!
//integers: scala.collection.immutable.IndexedSeq[Int] = !
Vector(10, 20, 30, 40, 50, 60, 70, 80, 90)
~ Translated ~!
(1 to 99) filter isEven filter ( _ % 5 == 0)
42. Some language features
⬤Strings: Interpolation and MultilineStrings!
⬤Option[Type]!
⬤Future[X]!
⬤XML erzeugen und bearbeiten!
⬤Reguläre Ausdrücke!
⬤Parallele Collections!
⬤Implicits
Clueda AG
42
43. String Interpolation
⬤String concatenation works with „+“!
!
!
⬤String interpolation: prepending String with „s“ marking Variable with $!
!
!
⬤Complex Expressions are enclosed within ${ }
Clueda AG
43
"hello" + " " + "world"!
//res2: String = hello world
val w = "world"!
s"hello $w"!
//res3: String = hello world
val w = "world"!
s"$w has length:${w.length}"!
//res4: String = world has length:5!
44. String Concatenation/Interpolation - Example
Clueda AG
44
val names = List("Roger","Felix", "Bene")!
!
for (name <- names) println("Hello" + name)!
!
//HelloRoger!
//HelloFelix!
//HelloBene
val names = List("Roger","Felix", "Bene")!
!
for (name <- names) println(s"Hello $name")!
!
//Hello Roger!
//Hello Felix!
//Hello Bene
45. Multiline String
⬤Multiline String is created by using """ """ instead of " " !
!
!
!
!
!
!
⬤allows embedding " in Strings and gets rid of double Escapes
Clueda AG
"""This!
| is a!
| multiline String!
| """!
!
res6: String =!
"This!
is a!
multiline String!
"
45
"""Hello "World"! """!
//res12: String = "Hello "World"! "
46. Combined example Strings
Clueda AG
46
val names = List("Roger","Felix", "Bene")!
!
for (name <- names) println(!
s"""Hello $name your name!
has length:${ name.size }!
and reads backwards as:"${ name.reverse}"!
"""!
)
Hello Roger your name!
has length:5!
and reads backwards as:"regoR"! !
Hello Felix your name!
has length:5!
and reads backwards as:"xileF"! !
Hello Bene your name!
has length:4!
and reads backwards as:"eneB"
47. String format - The f interpolator
⬤prepend String with f ““!
⬤Syntax like C printf
Clueda AG
47
def euroToDollar(euro: Double): Double = !
! ! euro * 1.352065!
!
val euro = List(1,2.5,5.12)!
!
euro map euroToDollar foreach { d =>!
println(f"Got $d%2.2f ($d)")!
}
Got 1,35 (1.352065)!
Got 3,38 (3.3801625)!
Got 6,92 (6.9225728)
48. The Option-Type
⬤Marks functions that may return a result but also may not return a result!
⬤Comes in two flavors: Some and None!
!
!
!
!
⬤like maybe in Haskell!
⬤A way to get around checking for null all the time
Clueda AG
48
val x : Option[_] = None!
//x: Option[_] = None!
!
val x : Option[_] = Some("Hello World!")!
//x: Option[_] = Some(Hello World!)
49. Option / List Comparison
⬤Option behaves like a list with one element!
!
!
⬤An empty Option is called None. None behaves like an empty list.
Clueda AG
49
List( 1 ) map (i => i + 0.5 ) !
//List[Double] = List(1.5)
Some( 1 ) map (i => i + 0.5 )!
//Option[Double] = Some(1.5)
val y : List[Int] = List()!
//y: List[Int] = List()!
!
y map (i => i+ 0.5)!
//List[Double] = List()
// Like an empty List!
val x : Option[Int] = None !
//x: Option[Int] = None!
x map (i => i+ 0.5)!
// Option[Double] = None
50. Option-Type Beispiel: Option vs. null
Clueda AG
50
val bigBangPHD = Map(!
"Leonard" -> "Ph.D.",!
"Sheldon" -> "Ph.D.,Sc.D",!
"Rajesh" -> "Ph.D"!
)!
!
val friends = List("Leonard","Sheldon","Rajesh","Howard")
bigBangPHD("Leonard")!
//res0: java.lang.String = Ph.D.!
!
bigBangPHD("Howard")!
java.util.NoSuchElementException: key not
found: Howard!
! at scala.collection.MapLike
$class.default(MapLike.scala:223)!
! at scala.collection.immutable.Map
$Map3.default(Map.scala:132)
bigBangPHD get "Leonard"!
//res1: Option[java.lang.String] !
= Some(Ph.D.)!
!
bigBangPHD.get("Sheldon")!
//res2: Option[java.lang.String] !
= Some(Ph.D., Sc.D)!
!
bigBangPHD.get("Howard")!
//res3: Option[java.lang.String] !
= None
51. Option -Type :Examples 1
⬤Used widely throughout Scala!
⬤many builtin methods to handle Option
Clueda AG
51
// Liste mit Options erzeugen !
friends map (bigBangPHD.get(_))!
friends map bigBangPHD.get!
//List[Option[java.lang.String]] = !
//List(Some(Ph.D.), Some(Ph.D.,Sc.D), Some(Ph.D), None)! !!
// flatten entfernt None und „entpackt“ Some(thing)!
friends map bigBangPHD.get flatten!
friends flatMap (f => bigBangPHD.get(f))!
/!/res5: List[java.lang.String] = List(Ph.D., Ph.D.,Sc.D, Ph.D)!
// for comprehensions wenden Operationen nur auf Some() an und verwerfen None!
for {!
! person <- friends!
! phd <- bigBangPHD get person!
} yield s"$person has a $phd"!
//List[java.lang.String] = !
//List(Leonard has a Ph.D., Sheldon has a Ph.D.,Sc.D, Rajesh has a Ph.D)
52. Option -Type : Examples 2‚
⬤Option ist tief in Scala integriert!
⬤Es existieren viele Methoden die mit Option umgehen können
// getOrElse erlaubt es einen Standardrückgabewert für None anzugeben, ansonsten wird Some(thing) „ausgepackt“!
friends!
! .map( n =>(n,bigBangPHD.get(n)) ) // creates Tuple!
! .map{ case (n,d) => !
! ! ! ! n + " " + d.getOrElse("Sheldon tells me you only have a master's degree.") !
! }! //res7: List[java.lang.String] = !
//List(Leonard Ph.D.,!
//Sheldon Ph.D.,Sc.D,!
//Rajesh Ph.D,!
//Howard Sheldon tells me you only have a master's degree.)! !
// Option Types besitzen Extraktoren für Pattern Matching!
friends map bigBangPHD.get zip friends map {!
Clueda AG
52
case (Some(phd), name ) => name + " : " + phd!
case (None, name) => name + " is just an engineer"!
}! !
//res10: List[java.lang.String] = List(Leonard : Ph.D.,!
//Sheldon : Ph.D.,Sc.D,!
//Rajesh : Ph.D,!
//Howard is just an engineer)
53. Futures
⬤Are a way to abstract over asynchronous computation!
⬤non blocking!
⬤can be used much like Option!
⬤used in many popular Scala libraries
Clueda AG
53
54. Futures - Plumbing
⬤Import com.scala.concurrent._ for future helpers!
⬤Every future needs an ExcecutionContext
Clueda AG
54
import scala.concurrent._!
import ExecutionContext.Implicits.global
56. Futures - Getting the result
⬤To get the result of a Future you have to block and wait!
!
!
⬤This is usually bad!
⬤Awaiting the result should happen as late as possible as it negates the benefits
one gets using futures
Clueda AG
56
import scala.concurrent.duration._! !
takeTime( Await.result( Future(printLinks), 10 seconds ))
scala> takeTime( Await.result( Future(printLinks), 10 seconds ))
warning: there were 1 feature warning(s); re-run with -feature for details
Url -> /favicon.gif
Url -> /stylesheets/refinery/style.css
Url -> /stylesheets/style.css?1380179036
Url -> /stylesheets/flexslider.css?1349423712
…
res30: (String, List[Unit]) = (took 1.976 s,List((), (), ()))
57. Futures - Composing
⬤As futures are Monads ( said it, done! ) they can be composed!
⬤The futures run asynchronously and will not wait for each other but await will
wait till the last of the futures has completed or the timeout is reached.
Clueda AG
57
def composedFutures: Future[(Unit,Unit,Unit)] = {!
! val f1 = Future( getAndPrintLinks("http://www.an-it.com") )!
! val f2 = Future( getAndPrintLinks("http://www.neumann.biz") )!
! val f3 = Future( getAndPrintLinks("http://www.clueda.com") )!
!
! for ( d1 <- f1 ; d2 <- f2 ; d3 <- f3) yield (d1,d2,d3)!
}
takeTime { Await.result(composedFutures,10 seconds) }
warning: there were 1 feature warning(s); re-run with -feature for details
Url -> /stylesheets/an-it.css?1339665275
Url -> mobile_stylesheets/mobile.css
Url -> /
Url -> ethnologie-studium
res21: (String, (Unit, Unit, Unit)) = (took 0.834 s,((),(),()))
58. XML in Scala
⬤XML is a first class language citizen as string is in Java or Ruby!
⬤It’s possible to embed XML in Scala source code and get syntax highlighting
Clueda AG
58
59. Scala - XML
⬤Xml can be written within scala sources!
⬤IDE s provide syntax-highlighting (Eclipse, Netbeans, IntelliJ)!
⬤Code can be embedded using { } within XML literals
Clueda AG
59
60. Emit XML - Example
Clueda AG
60
case class Book( title: String, pages: Int, year: Int) {!
!
def toXML = !
<book>!
<title>{title}</title>!
<pages>{pages toString}</pages>!
<year>{year toString}</year>!
</book>!
!
}!
!
val books = List( !
Book("Programming Scala", 883, 2012),!
Book("Programming Perl", 1104, 2000),!
Book("Necronomicon",666,666) !
)!
!
for ( book <- books) {!
println(book.toXML)!
}
62. Processing XML
⬤Scala provides an internal DSL influence providing a XPath like syntax (
instead of // and instead of / )!
⬤<xml></xml> "tag" : Shallow -Match!
⬤<xml></xml> "tag" : Deep -Match!
⬤<xml attribute=„wert“></xml> "@attribut" : Deep -Match on a XML attribute!
⬤(<xml></xml> "tag").text : Extracts the text value of an xml node
Clueda AG
62
63. processing XML - Example
Clueda AG
63
case class Book( title: String, pages: Int, year: Int) {!
def toXML = !
<book>!
<title>{title}</title>!
<pages>{pages}</pages>!
<year>{year}</year>!
</book>!
!
implicit def intToString(in : Int) : String = in.toString!
}!
!
object Book {!
def fromXML(bookXML: scala.xml.NodeSeq) : Book= {!
val title = (bookXML "title").text!
val pages = (bookXML "pages").text.toInt!
val year = (bookXML "year").text.toInt!
new Book(title, pages, year)!
}!
}
64. processing XML - Result
Clueda AG
64
val books = !
<books>!
<book>!
<title>Programming Scala</title>!
<pages>883</pages>!
<year>2012</year>!
</book>!
<book>!
<title>Programming Perl</title>!
<pages>1104</pages>!
<year>2000</year>!
</book>!
<book>!
<title>Necronomicon</title>!
<pages>666</pages>!
<year>666</year>!
</book>!
</books>! !
val booksInstances = (books „book") map Book.fromXML!
val booksPages = (books "pages").map(_.text.toInt)!
booksInstances: scala.collection.immutable.Seq[Book] = !
List(Book(Programming Scala,883,2012), Book(Programming Perl,1104,2000), Book(Necronomicon,666,666))!
booksPages: scala.collection.immutable.Seq[Int] = List(883, 1104, 666)
65. Regular Expressions
⬤Creating a regular Expression:.r aus einem String erzeugen: !
!
!
!
!
!
⬤Uses Java-Regex-Engine to create a NFA!
⬤Regex-Object also implement extractors for pattern matching
Clueda AG
65
// Using the Constructor!
new scala.util.matching.Regex("hrefs?=s?"([^"]+)"")!
//Changing a string to a regex with the .r method!
"hrefs?=s?"([^"]+)"".r!
// Using """ , no need to escape " and double escaping of !
"""hrefs?=s?"([^"]+)"""".r !
66. Regex - Usage
Clueda AG
66
import scala.io.Source!
!
val html = (Source fromURL "http://www.clueda.com").getLines mkString ""!
!
val urlExtractor = """hrefs?=s?"([^"]+)"""".r!
!
for ( urlExtractor(url) <- urlExtractor findAllIn html ) { !
! println(s"Url -> $url")!
}
67. first-order-functions / anonymous functions
⬤functions have a type like Integer or String!
⬤They can be arguments to function and passed around as values
Clueda AG
67
val y = (x: Int) => x * x!
//y: (Int) => Int = !
!
y apply 5!
// Int = 25!
!
y(5)!
// Int = 25!
!
val add = (x: Int, y: Int) => x + y!
// add: (Int, Int) => Int = !
!
add(1,2)!
// Int = 3
68. Implicits
⬤are introduced using the keyword implicit!
⬤trigger an automatic transformation!
⬤not stackable!
⬤shorter, more readable!
⬤may introduce „magic“!
⬤Pimp my library Pattern: Locally scopefied monkey patching
Clueda AG
68
69. Implicits: Example
⬤no more need to manually transform year to string when using xml!
⬤will also work for all other integers in scope of Book
Clueda AG
69
case class Book( title: String, pages: Int, year: Int) {!
def toXML = !
<book>!
<title>{title}</title>!
<pages>{pages}</pages>!
<year>{year}</year>!
</book>!
!
implicit def intToString(in : Int) : String = in.toString!
}
70. Parallel Collections
⬤Asynchronous, parallel processing to take advantage of multicore processors!
⬤.par transforms a Collection to it’s parallel counterpart!
⬤.seq transforms a parallel Collection to a sequential one!
⬤Parallel is implemented as a trait => can be used to create own par collections!
⬤Also works for Map
Clueda AG
70
71. Parallel Collections - Example
// Sequential!
(1 to 10) foreach println
Clueda AG
71
// Parallel!
(1 to 10).par foreach println
72. Parallele Collections - Examples II
Clueda AG
72
scala> tenTimes foreach println!
10!
80!
90!
60!
30!
70!
100!
20!
40!
50
scala> tenTimes.seq foreach println!
10!
20!
30!
40!
50!
60!
70!
80!
90!
100
// Unordered!
val tenTimes = (1 to 10).par map (_ * 10) !
tenTimes foreach println
// Unordered!
val tenTimes = (1 to 10).par map (_ * 10) !
tenTimes foreach println! !
//Ordered!
//.seq transforms a parallel collection to a sequential one!
tenTimes.seq foreach println
73. Build your own control structures
⬤Curried functions can be used to build control structures
Clueda AG
73
object ControlStructures {!
def unless( test: => Boolean)(action: => Any) = !
if (! test) action! !
def times( n: Int )(action: => Unit) {!
(1 to n) foreach { _ => action}!
}!
}
scala> import ControlStructures._!
/!/import ControlStructures._!
scala> times(2) { println("Hoorray :)")}!
Hoorray :)!
H!oorray :)!
scala> unless (5 < 10) { println("Math stopped working.") }!
/!/ Any = ()!
scala> val ifNot = unless (2 + 2 != 4) { "Math still works." }!
// Any = Math still works.!
74. Scala - Patterns
⬤Structural Typing!
⬤Pimp-My-Library-Pattern
Clueda AG
74
75. Structural Typing
⬤Classed are described by methods and return types they provide!
⬤Works like duck typing but the checking happens in compile time, not run time
Clueda AG
75
class Cowboy { def shout = "Yehaaw !" }!
class Pirate { def shout = "Arrrgh !" }!
!
def sayHelloTo( person : { def shout: String} ) = !
! s"Me : Hello!n $person shouts ${person.shout}"
val johnWayne = new Cowboy! !
sayHelloTo(johnWayne)!
scala> sayHelloTo(johnWayne)!
res4: String =!
Me : Hello!!
Cowboy@185f8f75 shouts
Yehaaw !
val guybrush = new Pirate! !
sayHelloTo(guybrush)!
scala> sayHelloTo(guybrush)!
res5: String =!
Me : Hello!!
Pirate@29c356d3 shouts Arrrgh !
76. Pimp-My-Library-Pattern
⬤Add new functions to existing libraries without changing the code!
⬤Like monkey patching!
⬤type safe!
⬤scoped
Clueda AG
76
77. Pimp-My-Library-Pattern : Example Source
Clueda AG
77
object PimpString {!
!
class WeatherString(s: String) {!
def ☀ = { println(s"$s sunny!") }!
def ☁ = "Dont't forget your ☂!“!
}!
!
implicit class ♔(name : String) {!
def hail = s"Hail to king $name"!
}!
!
implicit def pimpString(in: String) : WeatherString = !
!new WeatherString(in)!
}!
78. Pimp-My-Library-Pattern : Example Usage
Clueda AG
⬤Use with caution !
scala> import PimpString._!
import PimpString._! !
scala> "Monday is" ☀!
Monday is sunny!! !
scala> "???".☁!
res8: String = Dont't forget your ☂
scala> val anotherKing = ♔("Louis")!
anotherKing: PimpString.♔ = PimpString$$u2654@12359094! !
scala> val aKing = implicitly[♔]("George")!
aKing: PimpString.♔ = PimpString$$u2654@5081371! !
scala> aKing.hail!
res10: String = Hail to king George
78
scala> val guys = List("James", "Louis", "Franz-Ferdinand")!
guys: List[String] = List(James, Louis, Franz-Ferdinand)! !
scala> guys map (_.hail)!
res13: List[String] = List(Hail to king James, Hail to king Louis, Hail to king Franz-
Ferdinand)
80. Scala -imperative, object oriented, functional - Rules of the thumb
⬤functional if possible!
⬤Sometimes imperative is better and faster !
⬤start out with val and immutable collections,switch to var or mutable collections
if needed!
⬤Use object orientation to encapsulate side effects and imperative code
Clueda AG
80
81. Advantage of the functional approach
⬤short!
⬤no side effects -> easier to reason about!
⬤composeable
Clueda AG
81
82. Advantage of the imperative approach
⬤familiar!
⬤Eventually everything will be iterative after being translated to machine code
Clueda AG
82
83. Imperative vs. functional, Examples
var i = 0!
while (i < args.length) {!
if ( i != 0 )!
print(" ")!
print( args(i) )!
i += 1!
}!
println()
Clueda AG
83
Imperative Functional
var x = 1!
var sum = 0!
while (x <= 9999) {!
sum += x!
x += 1!
}!
(1 to 9999) foldLeft(0)(_ + _)
(1 to 9999) sum
println( args mkString " " )
println( !
args reduceOption ( (acc,arg ) => !
acc + " " + arg!
)!
)
84. Imperative vs. functional, Examples 2
Clueda AG
84
Imperative Functional
var i = null!
var data = gettingData()! !
if (data != null && data.size > 0) !
! i = data(0)!
else !
! i = 42!
val i = !
! if (data != null && data.size > 0)!
! ! data(0)!
! else!
! ! 42
val i = !
! gettingData().headOption getOrElse 42
85. Literatur:
⬤Wampler, D., & Payne, A. (2009). Programming Scala. Sebastopol, CA:
O'Reilly.!
⬤Odersky, M., Spoon, L., & Venners, B. (2008). Programming in Scala.
Mountain View, Calif: Artima.!
⬤Malayeri, M. “Pimp My Library” Is An Affront To Pimpers Of The World,
Everywhere!
⬤http://www.scala-lang.org!
⬤http://www.an-it.com
Clueda AG
85