Object Equality In Scala, means comparing two objects by their values and references.Generally, equality is ubiquitous in programming. It is also more tricky than it looks at first glance. This presentation looks at object equality in detail and gives some recommendations to consider when we design our own equality tests.
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
Principled way to design and implement functional domain models using some of the patterns of domain driven design. DDD, as the name suggests, is focused towards the domain model and the patterns of architecture that it encourages are also based on how we think of interactions amongst the basic abstractions of the domain. Of course the primary goal of the talk is to discuss how Scala and Zio 2 can be a potent combination in realizing the implementation of such models. This is not a talk on FP, the focus will be on how to structure and modularise an application based on some of the patterns of DDD.
Tagless Final Encoding - Algebras and Interpreters and also ProgramsPhilip Schwarz
Tagless Final Encoding - Algebras and Interpreters and also Programs - An introduction, through the work of Gabriel Volpe.
Slide deck home: http://fpilluminated.com/assets/tagless-final-encoding-algebras-interpreters-and-programs.html
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
The focus of the talk is to emphasize the importance of algebraic thinking when designing pure functional domain models. The talk begins with the definition of an algebra as consisting of a carrier type, a set of operations/functions and a set of laws on those operations. Using examples from the standard library, the talk shows how thinking of abstractions in terms of its algebra is more intuitive than discussing its operational semantics. The talk also discusses the virtues of parametricity and compositionality in designing proper algebras.
Algebras are compositional and help build larger algebras out of smaller ones. We start with base level types available in standard libraries and compose larger programs out of them. We take a real life use case for a domain model and illustrate how we can define the entire model using the power of algebraic composition of the various types. We talk about how to model side-effects as pure abstractions using algebraic effects. At no point we will talk about implementations.
At the end of the talk we will have a working model built completely out of the underlying algebra of the domain language.
Lambdas and Streams Master Class Part 2José Paumard
These are the slides of the talk we made with Stuart Marks at Devoxx Belgium 2018. This second part covers the Stream API, reduction and the Collector API.
What is the state of lambda expressions in Java 11? Lambda expressions are the major feature of Java 8, having an impact on most of the API, including the Streams and Collections API. We are now living the Java 11 days; new features have been added and new patterns have emerged. This highly technical Deep Dive session will visit all these patterns, the well-known ones and the new ones, in an interactive hybrid of lecture and laboratory. We present a technique and show how it helps solve a problem. We then present another problem, and give you some time to solve it yourself. Finally, we present a solution, and open for questions, comments, and discussion. Bring your laptop set up with JDK 11 and your favorite IDE, and be prepared to think!
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
The presentation is an introduction the hash algorithm application, dealing with random data and sorting it for fast accessing and implications with normal hashing techniques.
Free Monads are a powerful technique that can separate the representation of programs from the messy details of how they get run.
I'll go into the details of how they work, how to use them for fun and profit in your own code, and demonstrate a live Free Monad-driven tank game.
Supporting code at https://github.com/kenbot/free
Why functional programming and category theory strongly mattersPiotr Paradziński
Abstractions of Category Theory to define abstractions (Functor, Applicative, Monad, Comonad, Coyoneda) commonly used in functional programming (FP). Using definitions from Category Theory to reason about modular and composable design. Examples based on Haskell papers: Functional pearls translated to Scala.
The presentation is an introduction the hash algorithm application, dealing with random data and sorting it for fast accessing and implications with normal hashing techniques.
Free Monads are a powerful technique that can separate the representation of programs from the messy details of how they get run.
I'll go into the details of how they work, how to use them for fun and profit in your own code, and demonstrate a live Free Monad-driven tank game.
Supporting code at https://github.com/kenbot/free
Wrong provides a general assert method that takes a predicate block. Assertion failure messages are rich in detail. The Wrong idea is to replace all those countless assert\_this, assert\_that, should\_something library methods which only exist to give a more useful failure message than "assertion failed". Wrong replaces all of them in one fell swoop, since if you can write it in Ruby, Wrong can make a sensible failure message out of it.
Introducing Assignment invalidates the Substitution Model of Evaluation and v...Philip Schwarz
(download for better quality)
Introducing Assignment invalidates the Substitution Model of Evaluation and violates Referential Transparency
- as explained in SICP (the Wizard Book)
We have all seen repetitive code, maintained by cut+paste, that creates an object, calls a method, checks a return, calls a method, checks a return... all of it difficult to maintain because of its sheer size.
Object::Exercise replaces the pasted loops with data-driven code, the operation controlled by a data structure of methods, arguments, and expected return values. This replaces cut+paste with declarative data.
This talk describes O::E and shows a few ways to apply it for testing the MadMongers' Adventure game.
We <3 .rb
but - still .rb < perfect
This presentation shows some of the ways that this language, engineered for maximum programmer happiness and least surprise, can still have some nasty gotchas.
Principles of functional progrmming in scalaehsoon
a short outline on necessity of functional programming and principles of functional programming in Scala.
In the article some keyword are used but not explained (to keep the article short and simple), the interested reader can look them up in internet.
Getting Started with Apache Spark (Scala)Knoldus Inc.
In this session, we are going to cover Apache Spark, the architecture of Apache Spark, Data Lineage, Direct Acyclic Graph(DAG), and many more concepts. Apache Spark is a multi-language engine for executing data engineering, data science, and machine learning on single-node machines or clusters.
Secure practices with dot net services.pptxKnoldus Inc.
Securing .NET services is paramount for protecting applications and data. Employing encryption, strong authentication, and adherence to best coding practices ensures resilience against potential threats, enhancing overall cybersecurity posture.
Distributed Cache with dot microservicesKnoldus Inc.
A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm. Here we will look into implementation of Distributed Caching Strategy with Redis in Microservices Architecture focusing on cache synchronization, eviction policies, and cache consistency.
Introduction to gRPC Presentation (Java)Knoldus Inc.
gRPC, which stands for Remote Procedure Call, is an open-source framework developed by Google. It is designed for building efficient and scalable distributed systems. gRPC enables communication between client and server applications by defining a set of services and message types using Protocol Buffers (protobuf) as the interface definition language. gRPC provides a way for applications to call methods on a remote server as if they were local procedures, making it a powerful tool for building distributed and microservices-based architectures.
Using InfluxDB for real-time monitoring in JmeterKnoldus Inc.
Explore the integration of InfluxDB with JMeter for real-time performance monitoring. This session will cover setting up InfluxDB to capture JMeter metrics, configuring JMeter to send data to InfluxDB, and visualizing the results using Grafana. Learn how to leverage this powerful combination to gain real-time insights into your application's performance, enabling proactive issue detection and faster resolution.
Intoduction to KubeVela Presentation (DevOps)Knoldus Inc.
KubeVela is an open-source platform for modern application delivery and operation on Kubernetes. It is designed to simplify the deployment and management of applications in a Kubernetes environment. KubeVela is a modern software delivery platform that makes deploying and operating applications across today's hybrid, multi-cloud environments easier, faster and more reliable. KubeVela is infrastructure agnostic, programmable, yet most importantly, application-centric. It allows you to build powerful software, and deliver them anywhere!
Stakeholder Management (Project Management) PresentationKnoldus Inc.
A stakeholder is someone who has an interest in or who is affected by your project and its outcome. This may include both internal and external entities such as the members of the project team, project sponsors, executives, customers, suppliers, partners and the government. Stakeholder management is the process of managing the expectations and the requirements of these stakeholders.
Introduction To Kaniko (DevOps) PresentationKnoldus Inc.
Kaniko is an open-source tool developed by Google that enables building container images from a Dockerfile inside a Kubernetes cluster without requiring a Docker daemon. Kaniko executes each command in the Dockerfile in the user space using an executor image, which runs inside a container, such as a Kubernetes pod. This allows building container images in environments where the user doesn’t have root access, like a Kubernetes cluster.
Efficient Test Environments with Infrastructure as Code (IaC)Knoldus Inc.
In the rapidly evolving landscape of software development, the need for efficient and scalable test environments has become more critical than ever. This session, "Streamlining Development: Unlocking Efficiency through Infrastructure as Code (IaC) in Test Environments," is designed to provide an in-depth exploration of how leveraging IaC can revolutionize your testing processes and enhance overall development productivity.
Exploring Terramate DevOps (Presentation)Knoldus Inc.
Terramate is a code generator and orchestrator for Terraform that enhances Terraform's capabilities by adding features such as code generation, stacks, orchestration, change detection, globals, and more . It's primarily designed to help manage Terraform code at scale more efficiently . Terramate is particularly useful for managing multiple Terraform stacks, providing support for change detection and code generation 2. It allows you to create relationships between stacks to improve your understanding and control over your infrastructure . One of the key features of Terramate is its ability to detect changes at both the stack and module level. This capability allows you to identify which stacks and resources have been altered and selectively determine where you should execute commands.
Clean Code in Test Automation Differentiating Between the Good and the BadKnoldus Inc.
This session focuses on the principles of writing clean, maintainable, and efficient code in the context of test automation. The session will highlight the characteristics that distinguish good test automation code from bad, ultimately leading to more reliable and scalable testing frameworks.
Integrating AI Capabilities in Test AutomationKnoldus Inc.
Explore the integration of artificial intelligence in test automation. Understand how AI can enhance test planning, execution, and analysis, leading to more efficient and reliable testing processes. Explore the cutting-edge integration of Artificial Intelligence (AI) capabilities in Test Automation, a transformative approach shaping the future of software testing. This session will delve into practical applications, benefits, and considerations associated with infusing AI into test automation workflows.
State Management with NGXS in Angular.pptxKnoldus Inc.
NGXS is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations. In this session we will go through the main for components of NGXS -Store, Actions, State, and Select.
Authentication in Svelte using cookies.pptxKnoldus Inc.
Svelte streamlines authentication with cookies, offering a secure and seamless user experience. Effortlessly manage sessions by storing tokens in cookies, ensuring persistent logins. With Svelte's simplicity, implement robust authentication mechanisms, enhancing user security and interaction.
OAuth2 Implementation Presentation (Java)Knoldus Inc.
The OAuth 2.0 authorization framework is a protocol that allows a user to grant a third-party web site or application access to the user's protected resources, without necessarily revealing their long-term credentials or even their identity. It is commonly used in scenarios such as user authentication in web and mobile applications and enables a more secure and user-friendly authorization process.
Supply chain security with Kubeclarity.pptxKnoldus Inc.
Kube clarity is a comprehensive solution designed to enhance supply chain security within Kubernetes environments. Kube clarity enables organizations to identify and mitigate potential security threats throughout the software development and deployment process.
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
In this session, we will delve into the world of web scraping with JSoup, an open-source Java library. Here we are going to learn how to parse HTML effectively, extract meaningful data, and navigate the Document Object Model (DOM) for powerful web scraping capabilities.
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
Dive into the fundamental aspects of Akka gRPC and learn to leverage its power in building compact and efficient distributed systems. This session aims to equip attendees with the essential skills and knowledge to leverage Akka and gRPC effectively in building robust, scalable, and distributed applications.
Entity Core with Core Microservices.pptxKnoldus Inc.
How Developers can use Entity framework(ORM) which provides a structured and consistent way for microservices to interact with their respective database, prompting independence, scaliblity and maintainiblity in a distributed system, and also provide a high-level abstraction for data access.
Introduction to Redis and its features.pptxKnoldus Inc.
Join us for an interactive session where we'll cover the fundamentals of Redis, practical use cases, and best practices for incorporating Redis into your projects. Whether you're a developer, architect, or system administrator, this session will equip you with the knowledge to harness the full potential of Redis for your applications. Get ready to elevate your understanding of in-memory data storage and revolutionize the way you handle data in your projects with Redis
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™UiPathCommunity
In questo evento online gratuito, organizzato dalla Community Italiana di UiPath, potrai esplorare le nuove funzionalità di Autopilot, il tool che integra l'Intelligenza Artificiale nei processi di sviluppo e utilizzo delle Automazioni.
📕 Vedremo insieme alcuni esempi dell'utilizzo di Autopilot in diversi tool della Suite UiPath:
Autopilot per Studio Web
Autopilot per Studio
Autopilot per Apps
Clipboard AI
GenAI applicata alla Document Understanding
👨🏫👨💻 Speakers:
Stefano Negro, UiPath MVPx3, RPA Tech Lead @ BSP Consultant
Flavio Martinelli, UiPath MVP 2023, Technical Account Manager @UiPath
Andrei Tasca, RPA Solutions Team Lead @NTT Data
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
2. Object Equality In Java & Scala:
- Two equality comparisons:
1. == Operator
2. Equals()
- The == operator, which is the natural equality for value types and object indentity for
Refernce types in Java.
// This is Java
boolean isEqual(int x, int y){
return x == y; // Natural equality on value types
}
System.out.println(isEqual ( 421, 421)); //Output: True
//java.lang.Integer(Object)
boolean isEqual(Integer x, Integer y){
return x == y; // Reference equality on reference types
}
System.out.println(isEqual ( 421, 421)); //Output: False
3. - The == equality is reserved in Scala for the “ Natural ” equality of each type. The
equality operation == in scala is designed to be transparent with respect to the type's
representation.
- For value types, it is the natural (numeric or boolean) equality.
- For reference types, == is treated as an alias of the equals() inherited from object.
//This is Scala
scala> def isEqual(x : Int , y : Int) = x == y
isEqual: (x: Int, y: Int )Boolean
scala> isEqual( 421 , 421)
res8: Boolean = true
scala> def isEqual(x : Any , y : Any) = x == y
isEqual: (x: Any , y: Any)Boolean
scala> isEqual( 421 , 421)
res8: Boolean = true
4. String Comparisons:
- Scala, never fall into Java's well-known trap concerning string comparisons.
//This is Scala
scala> val x=“abcd”.substring(2)
x: java.lang.String = cd
scala> val y=“abcd”.substring(2)
y: java.lang.String = cd
scala> x == y
res7: Boolean = true
//This is Java
boolean isEquals(String x, String y){
return x.substring(2) == y.substring(2); //return x.substring(2).equals(y.substring(2));
//Output: true
}
String s1="abcd";
String s2="abcd";
System.out.println(isEquals(s1, s2)); //Output: false
5. Reference Equality:
- For refernce equality, Scala's class AnyRef defines an additional eq method, which
cannot be overridden and is implemented as reference equality(i. e., it behaves like ==
in Java for reference types).
scala> val x=new String(“abc”)
x: java.lang.String = abc
scala> val x=new String("abc")
x: java.lang.String = abc
scala> x == y
res13: Boolean = true // Value equality
scala> x eq y
res14: Boolean = false // Reference Equality
- There's also the negation of eq , which is called ne.
scala> x ne y
res14: Boolean = true
6. - For refernce equality, the behavior of == for new types can redefine by overriding the
equals method, which is always inherited from class Any.
- It is not possible to override == directly, as it is defined as a final method in class Any.
// defination of == in Any class
final def == (that : Any) : Boolean =
if ( null eq this) { null eq that }
else { this equals that }
7. Writing an Equality Method:
- Writing a correct equality method is surprisingly difficult in object-oriented languages.
- This is problematic, because equality is at the basis of many other things.
- Here are four common pitfalls that can cause inconsistent behavior when overriding
equals:
1. Defining equals with wrong signature
2. Changing equals without also changing hashCode
3. Defining equals in terms of mutable fields
4. Failing to define equals as an equivalence relation
8. Pitfall #1: Defining equals with wrong signature
class Point ( val x:Int, val y :Int) {
def equals (other: Point): Boolean = //Overloaded equals()
this.x == other.x && this.y == other.y
}
scala> val p1, p2 = new Point (1 , 2)
p1: Point = Point@1e0bb90
p2: Point = Point@139fb49
scala> val q= new Point( 2 , 3)
q: Point = Point@a44ec3
//Working OK
scala> p1 equals p2 res:0 Boolean : true
scala> p1 equals q res:0 Boolean : false
//Trouble
scala> val p2a: Any = p2 // Alias of p2
p2a: Any = Point@139fb49
// p2a calling equals() of Any class
scala> p1 equals p2a res:0 Boolean : false
9. Solution: Correct Signature
class Point ( val x:Int, val y :Int) {
// A better definition:Overriding equals of Any class
override def equals(other: Any) = other match {
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
scala> val p2a: Any = p2 // Alias of p2
p2a: Any = Point@139fb49
scala> p1 equals p2a res:0 Boolean : true
10. - A related pitfall is to define == with a wrong signature.
- If try to redefine == with the correct signature, which takes an argument of type Any, the
compiler will give an error because you try to override a final method of type Any.
- However, newcomers to Scala sometimes make two errors at once: They try to override ==
and they give it the wrong signature.
- For instance:
def ==(other: Point): Boolean = // Don’t do this! (User-defined == method)
- In that case, the user-defined == method is treated as an overloaded variant of the
same-named method class Any, and the program compiles.
- However, the behavior of the program would be just as dubious as if you had defined
equals with the wrong signature.
11. Pitfall #2: Changing equals without also changing hashCode
//Previously defined equals method
class Point ( val x:Int, val y :Int) {
// A better definition:Overriding equals of Any class
override def equals(other: Any) = other match {
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
scala> import scala.collection.mutable._
import scala.collection.mutable._
scala> val p1, p2 = new Point (1 , 2)
p1: Point = Point@1bef480
p2: Point = Point@1a6068c
//storing p1 to collection
scala> val coll = HashSet (p1)
coll: scala.collection.mutable.Set[Point] = Set(Point@62d74e)
scala> coll contains p2 res2: Boolean = false
12. - In fact, this outcome is not 100% certain. We might also get true from the experiment.
We can try with some other points with coordinates 1 and 2. Eventually, we’ll get one
which is not contained in the set.
hashSet(p1) contains p2
val p2
true val p1 val p2
false
hashSet Hash Bucket
Hash Bucket
Pitfall #2: Changing equals without also changing hashCode
13. - Wrong here is that Point redefined equals without also redefining hashCode.
- The problem was that the last implementation of Point violated the contract on hashCode as
defined for class Any:
If two objects are equal according to the equals method, then calling the
hashCode method on each of the two objects must produce the same integer result.
- In fact, it’s well known in Java that hashCode and equals should always be redefined
together.
- Furthermore, hashCode may only depend on fields that equals depends on.
- For the Point class, the following would be a suitable definition of hashCode:
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
- This is just one of many possible implementations of hashCode.
- Adding hashCode fixes the problems of equality when defining classes like Point.
14. class Point(val x: Int, val y: Int) {
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
override def equals(other: Any) = other match { // Redefine equals()
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
scala> val p1, p2 = new Point(1, 2)
p1: Point = Point@6bc
p2: Point = Point@6bc
scala> coll contains p2 res2: Boolean = true
15. Pitfall #3: Defining equals in terms of mutable fields:
- Consider the following slight variation of class Point:
class Point2(var x: Int, var y: Int) {
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
override def equals(other: Any) = other match { // Redefine equals()
case that: Point2 => this.x == that.x && this.y == that.y
case _ => false
}
}
scala> val p = new Point(1, 2) p: Point = Point@2b
scala> val coll = HashSet(p)
coll: scala.collection.mutable.Set[Point] = Set(Point@2b)
scala> coll contains p res5: Boolean = true
scala> p.x += 1 // Changing p.x value
scala> coll contains p res7: Boolean = false
scala> coll.elements contains p res7: Boolean = true
16. coll.elements contains p
true
p.x += 1
After change value it
(x:mutable) assign to wrong hash
bucket
p.x=1 p.x=2
coll contains p
coll false Hash Bucket
Hash Bucket
Pitfall #3: Defining equals in terms of mutable fields
- In a manner of speaking, the point p “dropped out of sight” in the set coll even though it
still belonged to its elements.
- If you need a comparison that takes the current state of an object into account, you
should usually name it something else, not equals.
17. Pitfall #4: Failing to define equals as an equivalence relation:
- In scala, Any class specifies that equals must implement an equivalence relation on
non-null objects:
• It is reflexive: for any non-null value x , the expression x.equals(x) should return true.
• It is symmetric: for any non-null values x and y, x.equals(y) should return true if and
only if y.equals(x) returns true.
• It is transitive: for any non-null values x, y, and z, if x.equals(y) returns true and
y.equals(z) returns true, then x.equals(z) should return true.
• It is consistent: for any non-null values x and y, multiple invocations of x.equals(y)
should consistently return true or consistently return false, provided
no information used in equals comparisons on the objects is modified.
• For any non-null value x, x.equals(null) should return false.
- The definition of equals developed so far for class Point satisfies the contract for equals.
- However, things become more complicated once subclasses are considered.
18. Symmetric Problem:
class Point(val x: Int, val y: Int) {
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
override def equals(other: Any) = other match { // Redefine equals()
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
object Color extends Enumeration {
val Red, Orange, Yellow, Green, Blue, Indigo, Violet = Value
}
class ColoredPoint(x: Int, y: Int, val color: Color.Value)
extends Point(x, y) { // Problem: equals not symmetric
override def equals(other: Any) = other match {
case that: ColoredPoint =>this.color == that.color &&
super.equals(that)
case _ => false
}
}
scala> val p = new Point(1, 2) p: Point = Point@2b
scala> val cp = new ColoredPoint(1, 2, Color.Red) cp: ColoredPoint =ColoredPoint@2b
scala> p equals cp res:0 Boolean : true
scala> cp equals p res:0 Boolean : false
19. Solution of Symmetric Problem but violated Transitivity contract:
class Point(val x: Int, val y: Int) {
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
override def equals(other: Any) = other match { // Redefine equals()
case that: Point => this.x == that.x && this.y == that.y
case _ => false
}
}
object Color extends Enumeration {
val Red, Orange, Yellow, Green, Blue, Indigo, Violet = Value
}
class ColoredPoint(x: Int, y: Int, val color: Color.Value)
extends Point(x, y) { // Problem: equals not transitive
override def equals(other: Any) = other match {
case that: ColoredPoint =>this.color == that.color &&
super.equals(that)
case that:Point=>that equals this //new case to make symmetric
case _ => false
}
}
scala> p equals cp res:0 Boolean : true
scala> cp equals p res:0 Boolean : true
20. - Here’s a sequence of statements that demonstrates transitive. Define a point and two
colored points of different colors, all at the same position:
scala> var redp=new ColoredPoint(1,2,Color.Red)
redp: ColoredPoint = ColoredPoint@6bc
scala> var bluep=new ColoredPoint(1,2,Color.Blue)
bluep: ColoredPoint = ColoredPoint@6bc
scala> var p=new Point(1,2)
p: Point = Point@6bc
scala> redp == p res1: Boolean = true
scala> p == bluep res1: Boolean = true
scala> redp == bluep res1: Boolean = false
- Hence, the transitivity clause of equals’s contract is violated.
- One way to make equals stricter is to always treat objects of different classes as different.
- That could be achieved by modifying the equals methods in classes Point and
ColoredPoint.
- In class Point, you could add an extra comparison that checks whether the run-time class
of the other Point is exactly the same as this Point’s class, as follows:
21. Solution of Transitivity Problem:
class Point(val x: Int, val y: Int) {
override def hashCode = 41 * (41 + x) + y // Redefine hashCode
override def equals(that: Any) = other match { // Redefine equals()
case that: Point => this.x == that.x && this.y == that.y
&& this.getClass == that.getClass
case _ => false
}
}
object Color extends Enumeration {
val Red, Orange, Yellow, Green, Blue, Indigo, Violet = Value
}
class ColoredPoint(x: Int, y: Int, val color: Color.Value)
extends Point(x, y) {
override def equals(that: Any) = other match {
case that: ColoredPoint =>(this.color == that.color)&& super.equals(that)
case _ => false
}
}
scala> redp == p res:0 Boolean : false
scala> p == bluep res:0 Boolean : false
scala> redp == bluep res:0 Boolean : false
22. - Here, an instance of class Point is considered to be equal to some other instance of the
same class only if the objects have the same coordinates and they have the same run-
time class.
- Meaning .getClass on either object returns the same value.
- The new definitions satisfy symmetry and transitivity because now every comparison
between objects of different classes yields false.
- So a colored point can never be equal to a point.