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.
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 provides an overview of Scala and discusses its advantages compared to other programming languages. Some key points:
- Scala is a multi-paradigm language that supports both object-oriented and functional programming. It runs on the JVM and can access Java libraries.
- Functional programming in Scala enables easier concurrency and scalability compared to imperative programming. Static typing also adds type safety.
- Scala provides flexibility to write code in different styles depending on one's skill level, without restricting creativity. Its REPL environment makes it easy to learn interactively.
- While Scala compilation times can be long, its hybrid approach enables gradual learning from both object-oriented and functional perspectives
This document provides an overview of the Scala programming language. Some key points:
- Scala runs on the Java Virtual Machine and was created by Martin Odersky at EPFL.
- It has been around since 2003 and the current stable release is 2.7.7. Release 2.8 beta 1 is due out soon.
- Scala combines object-oriented and functional programming. It has features like pattern matching, actors, XML literals, and more that differ from Java. Everything in Scala is an object.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
This document provides an overview of a 30-minute Scala tutorial covering Scala's core features like case classes, pattern matching, implicit classes, higher-order functions, and the Option monad. Scala is designed for concise syntax compared to Java, supports both object-oriented and functional programming, and is statically typed on the JVM. The tutorial demonstrates Scala concepts like implicit classes extending functionality, pattern matching for control flow, and using the Option monad to avoid null checks when chaining method calls.
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 provides an overview of Scala and discusses its advantages compared to other programming languages. Some key points:
- Scala is a multi-paradigm language that supports both object-oriented and functional programming. It runs on the JVM and can access Java libraries.
- Functional programming in Scala enables easier concurrency and scalability compared to imperative programming. Static typing also adds type safety.
- Scala provides flexibility to write code in different styles depending on one's skill level, without restricting creativity. Its REPL environment makes it easy to learn interactively.
- While Scala compilation times can be long, its hybrid approach enables gradual learning from both object-oriented and functional perspectives
This document provides an overview of the Scala programming language. Some key points:
- Scala runs on the Java Virtual Machine and was created by Martin Odersky at EPFL.
- It has been around since 2003 and the current stable release is 2.7.7. Release 2.8 beta 1 is due out soon.
- Scala combines object-oriented and functional programming. It has features like pattern matching, actors, XML literals, and more that differ from Java. Everything in Scala is an object.
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
This document provides an overview of a 30-minute Scala tutorial covering Scala's core features like case classes, pattern matching, implicit classes, higher-order functions, and the Option monad. Scala is designed for concise syntax compared to Java, supports both object-oriented and functional programming, and is statically typed on the JVM. The tutorial demonstrates Scala concepts like implicit classes extending functionality, pattern matching for control flow, and using the Option monad to avoid null checks when chaining method calls.
The document discusses differences between Ruby and Scala programming languages. Some key similarities include both being class-based object-oriented languages with functional features. Differences include Scala using explicit types while Ruby is dynamically typed, and Scala having separate concepts of methods and functions while Ruby blurs the distinction. The document also compares features like class definitions, collections, functions as values, and enhancing existing classes.
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/
Scala is a programming language that mixes object oriented and functional programming in a powerful and flexible way. While it can not be considered as a mainstream language, it has seen a growing adoption trend.An important ingredient for this diffusion is its complete interoperability with Java and the fact that it runs on a solid platform such as the JVM.
It is currently the 4th most loved programming language and the 2nd top paying technology of 2016 (StackOverflow Developers Survey).
These slides have been used for a 4h seminar at the University of Cagliari the 17th of December 2016
Scala is a multi-paradigm programming language that runs on the Java Virtual Machine. It is intended to be both object-oriented and functional. Scala is compatible with Java and allows Java code to interoperate with Scala code. Some key features of Scala include type inference, lazy evaluation, treating methods as variables, and support for both object-oriented and functional programming paradigms.
Scala is a modern programming language created by Martin Odersky that provides static typing and supports both object-oriented and functional programming paradigms. It compiles to Java bytecode and runs on the Java Virtual Machine (JVM), allowing it to interoperate with Java. Many consider Scala to be a better alternative to Java due to its concise and expressive syntax. Scala sees widespread use in production systems and has growing job opportunities for developers with Scala skills.
Starting with Scala : Frontier Developer's Meetup December 2010Derek Chen-Becker
This document provides an overview of the Scala programming language presented at a meetup event. It discusses Scala's history and pedigree, being created by Martin Odersky. It outlines some key aspects of Scala like being object-oriented, functional, and working on the JVM. The talk covers Scala fundamentals like immutable values, mutable variables, functions, and objects. It also discusses traits, classes, case classes and more Scala concepts.
I used these slides for a Scala workshop that I gave. They are based on these: http://www.scala-lang.org/node/4454. Thanks to Alf Kristian Støyle and Fredrik Vraalsen for sharing!
The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
This document introduces developing a Scala DSL for Apache Camel. It discusses using Scala techniques like implicit conversion, passing functions as parameters, by-name parameters and currying to build a DSL. It provides examples of building simple routes in the Scala DSL using these techniques and compares them to the Java DSL. It also covers some caveats like interactions between Java and Scala generics and operator precedence. The goal is to introduce basic Scala concepts and syntax that can be used to build a Scala DSL, using Apache Camel as an example.
Scala is a multi-paradigm programming language that runs on the JVM and combines object-oriented and functional programming. It is statically typed but has type inference for concise syntax. Scala is fully interoperable with Java and was created by Martin Odersky in 2003. Key features include classes, objects, traits, immutability by default, case classes, functional collections, and optional values to avoid null pointers.
This document provides an introduction to Scala for Java developers. It discusses that Scala is a hybrid object-oriented and functional language that runs on the JVM and interoperates well with Java. It highlights several features of Scala that allow for more concise code compared to Java, such as type inference, expressions instead of statements, higher-order functions, and case classes.
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Thoughtworks
3 years ago, Springer decided to use Scala on a large, strategic project. This talk is about the journey the development teams made. Why did they choose Scala in the first place? Did they get what they hoped for? What challenges and surprises did they encounter along the way? And, most importantly, are they still happy with their choice?
The document discusses Scala, a programming language designed to be scalable. It can be used for both small and large programs. Scala combines object-oriented and functional programming. It interoperates seamlessly with Java but allows developers to add new constructs like actors through libraries. The Scala community is growing, with industrial adoption starting at companies like Twitter.
This document provides an introduction to Scala by covering basic topics like packages, imports, classes, traits, control structures, and functions. It demonstrates Scala code for defining classes with fields, methods, and constructors. It shows how to use case classes, traits for composition, and for-comprehensions for iterating over collections. The document aims to highlight Scala's hybrid object-oriented and functional approach through code examples.
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.
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
Android is a fast-growing mobile operating system with millions of users worldwide.
Scala is a modern programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Why not combine both of them?
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.
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.
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.
Scala is a general purpose programming language that aims to be concise and elegant while avoiding issues with scaling to multiple processors. It provides both object oriented and functional programming features and integrates well with Java. Scala addresses scaling challenges through its support for actors which use asynchronous message passing instead of shared memory for concurrency.
The document discusses differences between Ruby and Scala programming languages. Some key similarities include both being class-based object-oriented languages with functional features. Differences include Scala using explicit types while Ruby is dynamically typed, and Scala having separate concepts of methods and functions while Ruby blurs the distinction. The document also compares features like class definitions, collections, functions as values, and enhancing existing classes.
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/
Scala is a programming language that mixes object oriented and functional programming in a powerful and flexible way. While it can not be considered as a mainstream language, it has seen a growing adoption trend.An important ingredient for this diffusion is its complete interoperability with Java and the fact that it runs on a solid platform such as the JVM.
It is currently the 4th most loved programming language and the 2nd top paying technology of 2016 (StackOverflow Developers Survey).
These slides have been used for a 4h seminar at the University of Cagliari the 17th of December 2016
Scala is a multi-paradigm programming language that runs on the Java Virtual Machine. It is intended to be both object-oriented and functional. Scala is compatible with Java and allows Java code to interoperate with Scala code. Some key features of Scala include type inference, lazy evaluation, treating methods as variables, and support for both object-oriented and functional programming paradigms.
Scala is a modern programming language created by Martin Odersky that provides static typing and supports both object-oriented and functional programming paradigms. It compiles to Java bytecode and runs on the Java Virtual Machine (JVM), allowing it to interoperate with Java. Many consider Scala to be a better alternative to Java due to its concise and expressive syntax. Scala sees widespread use in production systems and has growing job opportunities for developers with Scala skills.
Starting with Scala : Frontier Developer's Meetup December 2010Derek Chen-Becker
This document provides an overview of the Scala programming language presented at a meetup event. It discusses Scala's history and pedigree, being created by Martin Odersky. It outlines some key aspects of Scala like being object-oriented, functional, and working on the JVM. The talk covers Scala fundamentals like immutable values, mutable variables, functions, and objects. It also discusses traits, classes, case classes and more Scala concepts.
I used these slides for a Scala workshop that I gave. They are based on these: http://www.scala-lang.org/node/4454. Thanks to Alf Kristian Støyle and Fredrik Vraalsen for sharing!
The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
This document introduces developing a Scala DSL for Apache Camel. It discusses using Scala techniques like implicit conversion, passing functions as parameters, by-name parameters and currying to build a DSL. It provides examples of building simple routes in the Scala DSL using these techniques and compares them to the Java DSL. It also covers some caveats like interactions between Java and Scala generics and operator precedence. The goal is to introduce basic Scala concepts and syntax that can be used to build a Scala DSL, using Apache Camel as an example.
Scala is a multi-paradigm programming language that runs on the JVM and combines object-oriented and functional programming. It is statically typed but has type inference for concise syntax. Scala is fully interoperable with Java and was created by Martin Odersky in 2003. Key features include classes, objects, traits, immutability by default, case classes, functional collections, and optional values to avoid null pointers.
This document provides an introduction to Scala for Java developers. It discusses that Scala is a hybrid object-oriented and functional language that runs on the JVM and interoperates well with Java. It highlights several features of Scala that allow for more concise code compared to Java, such as type inference, expressions instead of statements, higher-order functions, and case classes.
Scala in-practice-3-years by Patric Fornasier, Springr, presented at Pune Sca...Thoughtworks
3 years ago, Springer decided to use Scala on a large, strategic project. This talk is about the journey the development teams made. Why did they choose Scala in the first place? Did they get what they hoped for? What challenges and surprises did they encounter along the way? And, most importantly, are they still happy with their choice?
The document discusses Scala, a programming language designed to be scalable. It can be used for both small and large programs. Scala combines object-oriented and functional programming. It interoperates seamlessly with Java but allows developers to add new constructs like actors through libraries. The Scala community is growing, with industrial adoption starting at companies like Twitter.
This document provides an introduction to Scala by covering basic topics like packages, imports, classes, traits, control structures, and functions. It demonstrates Scala code for defining classes with fields, methods, and constructors. It shows how to use case classes, traits for composition, and for-comprehensions for iterating over collections. The document aims to highlight Scala's hybrid object-oriented and functional approach through code examples.
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.
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
Android is a fast-growing mobile operating system with millions of users worldwide.
Scala is a modern programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Why not combine both of them?
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.
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.
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.
Scala is a general purpose programming language that aims to be concise and elegant while avoiding issues with scaling to multiple processors. It provides both object oriented and functional programming features and integrates well with Java. Scala addresses scaling challenges through its support for actors which use asynchronous message passing instead of shared memory for concurrency.
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.
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.
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.
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 is a powerful language for the JVM that is compatible with JDK 1.5+. It is a functional language maintained by Typesafe along with the community. Scala compiles to JVM bytecode like Java but has features like objects, traits, pattern matching and functional programming. James Gosling, the creator of Java, said that if he were to pick a language other than Java today, it would be Scala.
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.
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.
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.
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.
Develop realtime web with Scala and XitrumNgoc Dao
This document discusses a talk given by Ngoc Dao on developing realtime and distributed web applications with Scala and Xitrum. The talk covers:
1) An overview of Scala, including its functional features, object-oriented features, tools like SBT and REPL, and how to get started.
2) Using Scala for web development with the Xitrum framework, including routing, responding to requests, internationalization, and metrics.
3) Using Scala for concurrency with futures, actors, and Akka FSM.
4) Building realtime web applications with websockets, Socket.IO and SockJS.
5) Distributed systems with Akka remoting
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 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.
This ppt describes basics of scala upto collections covering both object oriented and functional programming concepts of the language.
References:Scala cookbook
Building Concurrent WebObjects applications with ScalaWO Community
This document discusses using Scala for concurrent programming in WebObjects applications. It begins by explaining why concurrent programming is important due to increasing numbers of processor cores. It then discusses challenges with traditional threading and locks and introduces the actor model as an easier and more scalable approach using message passing. The document demonstrates how to build concurrent WebObjects applications using Scala actors for processing tasks like video encoding. It shows how properties can configure WebObjects for concurrent requests and how ERXEC provides thread safety. Benchmarks show the Scala actor approach outperforms traditional threading. The document argues that Scala is a powerful, safe and easy language for concurrent programming in WebObjects.
This document provides an overview of the Scala programming language, including what it is, its toolchain, basic syntax examples comparing it to Java, built-in support for XML, actors, and advantages and disadvantages. Scala is an object-functional language that runs on the JVM and is intended to be a "better Java". It has features like XML support, an actor model for concurrency, and combines object-oriented and functional programming paradigms, but its ecosystem and compiler can be slow and syntax for some functional features is verbose.
- 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
Ash Furrow shares his recent real-world experience with Swift as a case study in an evaluation of Swift's production readiness. He provides a chance of taking advantage of the lessons they learned to make the best decisions about Swift.
Building the perfect HolidaySearch for HolidayCheck with ElasticsearchAndreas Neumann
Talk I gave on Elastic{ON} in Munich about the development of a search application at HolidayChek and which approches helped us to achieve a good search experience.
The document discusses different ways to structure tests and summarize test results in software projects. It recommends structuring test code in separate source folders from main code, and organizing tests by package to mirror the structure of the code being tested. The document also outlines different methods for running tests, such as through a continuous integration system, IDE, or build tool like SBT. Finally, it describes generating test result summaries in both human-readable formats in the terminal as well as machine-readable formats like JUnit XML that capture details of failed and passed tests.
Scala : Monads for the Pragmatic Programmer , Composition with Stackable TraitsAndreas Neumann
Der Workshop bietet einen Überblick über diverese Neuerungen in Scala wie Future- und Try- Monaden und zeigt wie man mit Stackable Traits composition realisiern kann. Es ahndelt sich um einen Workshop mit Live-Coding-Teil Im Detal werden folgende Themen behandelt:
Was ist eine Monade, was für Vorteile bringt es für Entwickler das Konzept zu kennen
map, flatMap, filter und for-Comprehensions
Monaden in Scala:
Option-Monade
Either-Monade
Try (Monadenartig)
Future
Composition mit Stackable Traits
Beispiel zur Dispatch Library (kurz)
Specs 2 : Acceptance-Test-Notation
Dieser Vortrag richtet sich an Anwender und an Einsteiger in das Thema Soziale Netzwerke (Social Network Services, SNS).
Es werden die bekanntesten Vertreter vorgestellt, darauf folgt ein Teil der die wichtigsten Komponenten eines SNS erläutert.
Dies wird anhand von Praxisbeispielen vertieft.
In einem zweiten Teil wird auf Chancen und Risiko eingegangen.
Mögliche Sicherheitseinstellungen werden besprochen, und es wird auf Stolperstellen und Unklarheiten in den Interfaces bekannter Anbieter hingewiesen.
Gas agency management system project report.pdfKamal Acharya
The project entitled "Gas Agency" is done to make the manual process easier by making it a computerized system for billing and maintaining stock. The Gas Agencies get the order request through phone calls or by personal from their customers and deliver the gas cylinders to their address based on their demand and previous delivery date. This process is made computerized and the customer's name, address and stock details are stored in a database. Based on this the billing for a customer is made simple and easier, since a customer order for gas can be accepted only after completing a certain period from the previous delivery. This can be calculated and billed easily through this. There are two types of delivery like domestic purpose use delivery and commercial purpose use delivery. The bill rate and capacity differs for both. This can be easily maintained and charged accordingly.
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Applications of artificial Intelligence in Mechanical Engineering.pdfAtif Razi
Historically, mechanical engineering has relied heavily on human expertise and empirical methods to solve complex problems. With the introduction of computer-aided design (CAD) and finite element analysis (FEA), the field took its first steps towards digitization. These tools allowed engineers to simulate and analyze mechanical systems with greater accuracy and efficiency. However, the sheer volume of data generated by modern engineering systems and the increasing complexity of these systems have necessitated more advanced analytical tools, paving the way for AI.
AI offers the capability to process vast amounts of data, identify patterns, and make predictions with a level of speed and accuracy unattainable by traditional methods. This has profound implications for mechanical engineering, enabling more efficient design processes, predictive maintenance strategies, and optimized manufacturing operations. AI-driven tools can learn from historical data, adapt to new information, and continuously improve their performance, making them invaluable in tackling the multifaceted challenges of modern mechanical engineering.
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
Rainfall intensity duration frequency curve statistical analysis and modeling...bijceesjournal
Using data from 41 years in Patna’ India’ the study’s goal is to analyze the trends of how often it rains on a weekly, seasonal, and annual basis (1981−2020). First, utilizing the intensity-duration-frequency (IDF) curve and the relationship by statistically analyzing rainfall’ the historical rainfall data set for Patna’ India’ during a 41 year period (1981−2020), was evaluated for its quality. Changes in the hydrologic cycle as a result of increased greenhouse gas emissions are expected to induce variations in the intensity, length, and frequency of precipitation events. One strategy to lessen vulnerability is to quantify probable changes and adapt to them. Techniques such as log-normal, normal, and Gumbel are used (EV-I). Distributions were created with durations of 1, 2, 3, 6, and 24 h and return times of 2, 5, 10, 25, and 100 years. There were also mathematical correlations discovered between rainfall and recurrence interval.
Findings: Based on findings, the Gumbel approach produced the highest intensity values, whereas the other approaches produced values that were close to each other. The data indicates that 461.9 mm of rain fell during the monsoon season’s 301st week. However, it was found that the 29th week had the greatest average rainfall, 92.6 mm. With 952.6 mm on average, the monsoon season saw the highest rainfall. Calculations revealed that the yearly rainfall averaged 1171.1 mm. Using Weibull’s method, the study was subsequently expanded to examine rainfall distribution at different recurrence intervals of 2, 5, 10, and 25 years. Rainfall and recurrence interval mathematical correlations were also developed. Further regression analysis revealed that short wave irrigation, wind direction, wind speed, pressure, relative humidity, and temperature all had a substantial influence on rainfall.
Originality and value: The results of the rainfall IDF curves can provide useful information to policymakers in making appropriate decisions in managing and minimizing floods in the study area.
AI for Legal Research with applications, toolsmahaffeycheryld
AI applications in legal research include rapid document analysis, case law review, and statute interpretation. AI-powered tools can sift through vast legal databases to find relevant precedents and citations, enhancing research accuracy and speed. They assist in legal writing by drafting and proofreading documents. Predictive analytics help foresee case outcomes based on historical data, aiding in strategic decision-making. AI also automates routine tasks like contract review and due diligence, freeing up lawyers to focus on complex legal issues. These applications make legal research more efficient, cost-effective, and accessible.
Comparative analysis between traditional aquaponics and reconstructed aquapon...bijceesjournal
The aquaponic system of planting is a method that does not require soil usage. It is a method that only needs water, fish, lava rocks (a substitute for soil), and plants. Aquaponic systems are sustainable and environmentally friendly. Its use not only helps to plant in small spaces but also helps reduce artificial chemical use and minimizes excess water use, as aquaponics consumes 90% less water than soil-based gardening. The study applied a descriptive and experimental design to assess and compare conventional and reconstructed aquaponic methods for reproducing tomatoes. The researchers created an observation checklist to determine the significant factors of the study. The study aims to determine the significant difference between traditional aquaponics and reconstructed aquaponics systems propagating tomatoes in terms of height, weight, girth, and number of fruits. The reconstructed aquaponics system’s higher growth yield results in a much more nourished crop than the traditional aquaponics system. It is superior in its number of fruits, height, weight, and girth measurement. Moreover, the reconstructed aquaponics system is proven to eliminate all the hindrances present in the traditional aquaponics system, which are overcrowding of fish, algae growth, pest problems, contaminated water, and dead fish.
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...shadow0702a
This document serves as a comprehensive step-by-step guide on how to effectively use PyCharm for remote debugging of the Windows Subsystem for Linux (WSL) on a local Windows machine. It meticulously outlines several critical steps in the process, starting with the crucial task of enabling permissions, followed by the installation and configuration of WSL.
The guide then proceeds to explain how to set up the SSH service within the WSL environment, an integral part of the process. Alongside this, it also provides detailed instructions on how to modify the inbound rules of the Windows firewall to facilitate the process, ensuring that there are no connectivity issues that could potentially hinder the debugging process.
The document further emphasizes on the importance of checking the connection between the Windows and WSL environments, providing instructions on how to ensure that the connection is optimal and ready for remote debugging.
It also offers an in-depth guide on how to configure the WSL interpreter and files within the PyCharm environment. This is essential for ensuring that the debugging process is set up correctly and that the program can be run effectively within the WSL terminal.
Additionally, the document provides guidance on how to set up breakpoints for debugging, a fundamental aspect of the debugging process which allows the developer to stop the execution of their code at certain points and inspect their program at those stages.
Finally, the document concludes by providing a link to a reference blog. This blog offers additional information and guidance on configuring the remote Python interpreter in PyCharm, providing the reader with a well-rounded understanding of the process.
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...PriyankaKilaniya
Energy efficiency has been important since the latter part of the last century. The main object of this survey is to determine the energy efficiency knowledge among consumers. Two separate districts in Bangladesh are selected to conduct the survey on households and showrooms about the energy and seller also. The survey uses the data to find some regression equations from which it is easy to predict energy efficiency knowledge. The data is analyzed and calculated based on five important criteria. The initial target was to find some factors that help predict a person's energy efficiency knowledge. From the survey, it is found that the energy efficiency awareness among the people of our country is very low. Relationships between household energy use behaviors are estimated using a unique dataset of about 40 households and 20 showrooms in Bangladesh's Chapainawabganj and Bagerhat districts. Knowledge of energy consumption and energy efficiency technology options is found to be associated with household use of energy conservation practices. Household characteristics also influence household energy use behavior. Younger household cohorts are more likely to adopt energy-efficient technologies and energy conservation practices and place primary importance on energy saving for environmental reasons. Education also influences attitudes toward energy conservation in Bangladesh. Low-education households indicate they primarily save electricity for the environment while high-education households indicate they are motivated by environmental concerns.
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
3. About Scala
‣ A JVM Languge
‣ mutltiparadigmatic
‣ functional object orientated
4. The father of Scala - Martin Odersky
‣ Professor EPFL
‣ Java-Compiler
‣ Java 1.4 Generics
‣ PIZZA
‣ Scala
‣ Co-Founder Typesafe
5. The company behind Scala -
‣ Training
‣ Consulting
‣ Scala
‣ Actor
‣ Play
6. Who is using Scala
‣ Xerox
‣ Twitter
‣ Foursquare
‣ Sony
‣ Siemens
‣ clueda
‣ …
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
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
10. Scala - compiler / scalac
‣ the compiler is called
scalac
‣ The sources are
compiled to Java byte
code
‣ *.class
‣ run class with scala
<name>
11. Scripting with Scala - Unix
‣ Scala can be used as scripting
language
‣ change mode to excuteable or run
by sh
#!/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
::#!!
@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
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.
"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
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!
^
Example: val and var
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.
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
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
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
27. Example: A scala class
‣ Instances are created with new <ClassName>
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
29. Scala Object - Example
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
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
32. Case Class - Example
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
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
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
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
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
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
40. Matching Example
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"!
}
books: List[Any] = List(Book(Programming Scala,883,2012), Book(Programming Pearl,1104,2000), Book(Necronomicon,666,666), Ein String, 5,
42)
bookComments: 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)
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
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
43. ‣ String concatenation works with „+“
!
‣ String interpolation: prepending String with „s“ marking Variable with $
!
‣ Complex Expressions are enclosed within ${ }
String Interpolation
"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
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
"""This!
| is a!
| multiline String!
| """!
!
res6: String =!
"This!
is a!
multiline String!
"!
"""Hello "World"! """!
//res12: String = "Hello "World"! "
46. Combined example Strings
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
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
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.
List( 1 ) map (i => i + 0.5 ) !
//List[Double] = List(1.5)
val y : List[Int] = List()!
//y: List[Int] = List()!
!
y map (i => i+ 0.5)!
//List[Double] = List()
Some( 1 ) map (i => i + 0.5 )!
//Option[Double] = Some(1.5)
// 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
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)
val bigBangPHD = Map(!
"Leonard" -> "Ph.D.",!
"Sheldon" -> "Ph.D.,Sc.D",!
"Rajesh" -> "Ph.D"!
)!
!
val friends = List("Leonard","Sheldon","Rajesh","Howard")
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
// 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‚
// 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 {!
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
54. Futures - Plumbing
‣ Import com.scala.concurrent._ for future helpers
‣ Every future needs an ExcecutionContext
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
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.
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
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
60. Emit XML - Example
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
63. processing XML - Example
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)!
}!
}!
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
// 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
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
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
69. Implicits: Example
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!
}
‣ no more need to manually transform year to string when using xml
‣ will also work for all other integers in scope of Book
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
71. Parallel Collections - Example
// Sequential!
(1 to 10) foreach println
// Parallel!
(1 to 10).par foreach println
72. Parallele Collections - Examples II
// 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
scala> tenTimes.seq foreach println
10
20
30
40
50
60
70
80
90
100
scala> tenTimes foreach println
10
80
90
60
30
70
100
20
40
50
73. Build your own control structures
‣ Currified functions can be used to build control structures
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 :)!
Hoorray :)!
!
scala> unless (5 < 10) { println("Math stopped working.") }!
// Any = ()!
!
scala> val ifNot = unless (2 + 2 != 4) { "Math still works." }!
// Any = Math still works.!
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
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
77. Pimp-My-Library-Pattern : Example Source
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
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
‣ Use with caution !
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
81. Advantage of the functional approach
‣ short
‣ no side effect -> easier to reason about
‣ composable
82. Advantage of the imperative approach
‣ familar
‣ Eventually everything will be iterative after being translated to machine code
83. Imperative vs. functional, Examples
Imperative Functional
var i = 0!
while (i < args.length) {!
if ( i != 0 )!
print(" ")!
print( args(i) )!
i += 1!
}!
println()!
var x = 1!
var sum = 0!
while (x <= 9999) {!
sum += x!
x += 1!
}!
(1 to 9999) foldLeft(0)(_ + _)
(1 to 9999) sum
println( !
args reduceOption ( (acc,arg ) => !
acc + " " + arg!
)!
)!
println( args mkString " " )
84. Imperative vs. functional, Examples 2
Imperative Functional
var i = null!
var data = gettingData()!
!
if (data != null && data.size > 0) !
! i = data(0)!
else !
! i = 42! val i = !
! gettingData().headOption getOrElse 42
val i = !
! if (data != null && data.size > 0)!
! ! data(0)!
! else!
! ! 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