I gave this presentation on January 14, 2010 to the Atlanta Scala user group. It covers Scala's implementation of operator overloading, as well as touching on implicit conversions.
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.
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Wim Vanderbauwhede
This talk is about two Perl modules (Call:Haskell and Functional::Types) I developed to call Haskell functions as transparently as possible.
In general, the only way to guarantee the correctness of the types of the function arguments in Haskell is to ensure they are well-typed in Perl. So I ended up writing a Haskell-inspired type system for Perl. In this talk I will first discuss the approach I took to call Haskell from Perl, and then the reasons why a type system is needed, and the actual type system I developed. The type system is based on "prototypes", functions that create type descriptors, and a small API of functions to create type constructors and manipulate the types. The system is type checked at run time and supports sum types, product types, function types and polymorphism. The approach is not Perl-specific and suitable for other dynamic languages.
https://github.com/wimvanderbauwhede
These are the slides of the talk I gave at the Dyla'14 workshop (http://conferences.inf.ed.ac.uk/pldi2014/). It's about monads for languages like Perl, Ruby and LiveScript.
The source code is available at
https://github.com/wimvanderbauwhede/Perl-Parser-Combinators
https://github.com/wimvanderbauwhede/parser-combinators-ls
Don't be put off by the word monad or the maths. This is basically a very practical way for doing tasks such as parsing.
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.
Perl and Haskell: Can the Twain Ever Meet? (tl;dr: yes)Wim Vanderbauwhede
This talk is about two Perl modules (Call:Haskell and Functional::Types) I developed to call Haskell functions as transparently as possible.
In general, the only way to guarantee the correctness of the types of the function arguments in Haskell is to ensure they are well-typed in Perl. So I ended up writing a Haskell-inspired type system for Perl. In this talk I will first discuss the approach I took to call Haskell from Perl, and then the reasons why a type system is needed, and the actual type system I developed. The type system is based on "prototypes", functions that create type descriptors, and a small API of functions to create type constructors and manipulate the types. The system is type checked at run time and supports sum types, product types, function types and polymorphism. The approach is not Perl-specific and suitable for other dynamic languages.
https://github.com/wimvanderbauwhede
These are the slides of the talk I gave at the Dyla'14 workshop (http://conferences.inf.ed.ac.uk/pldi2014/). It's about monads for languages like Perl, Ruby and LiveScript.
The source code is available at
https://github.com/wimvanderbauwhede/Perl-Parser-Combinators
https://github.com/wimvanderbauwhede/parser-combinators-ls
Don't be put off by the word monad or the maths. This is basically a very practical way for doing tasks such as parsing.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
Introduction to Functional Programming in JavaScripttmont
A presentation I did for work on functional programming. It's meant as an introduction to functional programming, and I implemented the fundamentals of functional programming (Church Numerals, Y-Combinator, etc.) in JavaScript.
OOP and FP - Become a Better ProgrammerMario Fusco
The story of Simon, an experienced OOP Java developer, exposed to the new lambda features of JDK 8. His friend Mario, a long-bearded FP geek, will try to convince him that FP can help him develop more readable and maintainable code. A journey into the discovery of the main new feature - lambda expressions - of JDK 8
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
While Google is adding Kotlin as an official Android language, we're also expanding our research on this language. It’s developed by JetBrains, and the fact that these are the people behind a suite of IDEs, such as IntelliJ and ReSharper, really shines through in Kotlin. It’s pragmatic and concise and makes coding a satisfying and efficient experience.
Although Kotlin compiles to both JavaScript and soon machine code, I’ll focus on its prime environment, the JVM.
Please see my presentation to learn more!
This presentation explains few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with the code snippet.
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin's standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.
The event will be led by Zoltan Domahidi (Senior Kotlin Software Engineer at Magyar Telekom).
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
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.
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
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
20 Comprehensive Checklist of Designing and Developing a WebsitePixlogix Infotech
Dive into the world of Website Designing and Developing with Pixlogix! Looking to create a stunning online presence? Look no further! Our comprehensive checklist covers everything you need to know to craft a website that stands out. From user-friendly design to seamless functionality, we've got you covered. Don't miss out on this invaluable resource! Check out our checklist now at Pixlogix and start your journey towards a captivating online presence today.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Full-RAG: A modern architecture for hyper-personalizationZilliz
Mike Del Balso, CEO & Co-Founder at Tecton, presents "Full RAG," a novel approach to AI recommendation systems, aiming to push beyond the limitations of traditional models through a deep integration of contextual insights and real-time data, leveraging the Retrieval-Augmented Generation architecture. This talk will outline Full RAG's potential to significantly enhance personalization, address engineering challenges such as data management and model training, and introduce data enrichment with reranking as a key solution. Attendees will gain crucial insights into the importance of hyperpersonalization in AI, the capabilities of Full RAG for advanced personalization, and strategies for managing complex data integrations for deploying cutting-edge AI solutions.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
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.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
2. First Things First
Working with Java since 1996
Playing with Scala for not-quite-a-year
Originally a blog post on joeygibson.com
See the original at http://bit.ly/wNvAl
Based on example from Programming Scala, by
Venkat Subramaniam
3. What Is Operator Overloading?
A language facility that allows developers to define
behavior for symbols like +, -, / for their own
classes, mimicking built-in operators
C++, Smalltalk, Ruby, lots of others have it
Java does not have it
Except + for String concatenation
BigDecimal, BigInteger, etc. would be nicer to use with
operators
4. The Basics
Technically, Scala does not have operator
overloading
Operatorsare just methods
Any method taking 0/1 argument can be called as an
operator
foo doSomething “x” is the same as foo.doSomething(“x”)
foo + 23 is the same as foo.+(23)
You can define both binary and unary operators
Only +, -, ~ and ! can be used as unary operators
As with binary operators, it’s just a method and
-foo is the same as foo.unary_-
5. What About Precedence?
Scala looks at the first character of the operator
name
All other special chars
*/%
+-
:
=!
<>
&
^
|
All letters
All assignment operators
6. Operator Naming
Typically, you would use arithmetic operator
symbols, but you don’t have to
Since operators are just methods, you can use non-
standard characters
Δ,λ, γ, Ω, etc.
Neat/useful, but use sparingly, unless it makes your
code easier to read and/or maintain
If the last character in an operator name is a colon,
that method associates to the right
8. ComplexTest.scala
package com.joeygibson.oopres
import org.junit.runner.RunWith
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class ComplexTest extends FlatSpec with ShouldMatchers {
"A Complex" should "sum up to 4-9i" in {
val c1 = new Complex(1, 2)
val c2 = new Complex(2, -3)
val c3 = c1 + c2
val res = c1 + c2 * c3
res.toString should equal ("4-9i")
}
}
9. Interesting Naming Examples
package com.joeygibson.oopres
import org.apache.commons.lang.StringUtils
class Fragment(val text: String) {
override def toString = text
def Δ(other: Fragment): Fragment = {
val diff = StringUtils.difference(text, other.text)
new Fragment(diff)
}
def ::(other: Fragment): Fragment = {
new Fragment(text + " || " + other.text)
}
}
10. Testing Interesting Names
package com.joeygibson.oopres
@RunWith(classOf[JUnitRunner])
class FragmentTest extends FlatSpec with ShouldMatchers {
it should "return proper differences" in {
val f0 = new Fragment("Scala is groovy")
val f1 = new Fragment("Scala is cool")
val diff = f0 Δ f1
diff.toString should equal("cool")
}
it should "concatenate properly" in {
val f0 = new Fragment("First Fragment")
val f1 = new Fragment("Second Fragment")
val f2 = f0 :: f1
f2.toString should equal ("Second Fragment || First Fragment")
}
}
11. You Can Even Get Silly…
package com.joeygibson.oopres
class Absurdity(val text: String) {
def //(other: Absurdity) = {
new Absurdity(text + ", " + other.text)
}
def //(other: Absurdity) = {
new Absurdity(other.text + ", " + text)
}
override def toString = text
}
12. Testing the Silliness
package com.joeygibson.oopres
@RunWith(classOf[JUnitRunner])
class AbsurdityTest extends FlatSpec with ShouldMatchers {
it should "do something absurd" in {
val a = new Absurdity("foo")
val b = new Absurdity("bar")
val c = a // b
c.toString should equal ("foo, bar")
}
it should "do something equally absurd" in {
val a = new Absurdity("foo")
val b = new Absurdity("bar")
val c = a // b
c.toString should equal ("bar, foo")
}
}
13. Arguments of Different Types
Define multiple versions of method, taking different
types
Use Implicit conversions
14. Multiple Defs of Operator
package com.joeygibson.oopres
class Complex2(val real: Int, val imaginary: Int) {
def +(operand: Complex2): Complex2 = {
new Complex2(real + operand.real, imaginary + operand.imaginary)
}
def +(operand: Int): Complex2 = this + new Complex2(operand, 0)
def *(operand: Complex2): Complex2 = {
new Complex2(real * operand.real - imaginary * operand.imaginary,
real * operand.imaginary + imaginary * operand.real)
}
def *(operand: Int): Complex2 = this * new Complex2(operand, 1)
def unary_- = new Complex2(-real, imaginary)
override def toString() = {
real + (if (imaginary < 0) "" else "+") + imaginary + "i"
}
}
15. Testing Multiple Defs
package com.joeygibson.oopres
@RunWith(classOf[JUnitRunner])
class Complex2Test extends FlatSpec with ShouldMatchers {
it should "convert int to Complex2" in {
val c = new Complex2(1, 2)
val d = c + 23
d.toString should equal ("24+2i")
}
// it should "convert int to Complex2, reversed" in {
// val c = new Complex2(1, 2)
// val d: Complex2 = 23 + c
//
// d.toString should equal ("24+2i")
// }
}
16. Implicit Conversions
The implicit function must be in scope
It can live in the companion object of either class
under consideration
Be careful with implicits, especially when using
common types
18. Testing Implicits
package com.joeygibson.oopres
@RunWith(classOf[JUnitRunner])
class Complex3Test extends FlatSpec with ShouldMatchers {
it should "convert int to Complex3" in {
val c = new Complex3(1, 2)
val d = c + 23
d.toString should equal ("24+2i")
}
it should "convert int to Complex3, reversed" in {
import com.joeygibson.oopres.Complex3.intToComplex3
val c = new Complex3(1, 2)
val d: Complex3 = 23 + c
d.toString should equal ("24+2i")
}
}
19. Using Both
package com.joeygibson.oopres
object Complex4 {
implicit def intToComplex4(anInt: Int): Complex4 = {
printf("Implicitly converting to Complex4n")
new Complex4(anInt, 0)
}
}
class Complex4(val real: Int, val imaginary: Int) {
def +(operand: Complex4): Complex4 = {
new Complex4(real + operand.real, imaginary + operand.imaginary)
}
def +(operand: Int): Complex4 = this + new Complex4(operand, 0)
def *(operand: Complex4): Complex4 = {
new Complex4(real * operand.real - imaginary * operand.imaginary,
real * operand.imaginary + imaginary * operand.real)
}
def *(operand: Int): Complex4 = this * new Complex4(operand, 0)
def unary_- = new Complex4(-real, imaginary)
override def toString() = {
real + (if (imaginary < 0) "" else "+") + imaginary + "i"
}
}
20. You Can’t Use ++ as Prefix
package com.joeygibson.oopres
class MyNumber(private var num: Int) {
def number: Int = num
override def toString = num.toString
def ++ = {
val n = num
num += 1
new MyNumber(n)
}
def unary_++ = {
num += 1
this
}
}
21. The First One Works, The Second…
package com.joeygibson.oopres
@RunWith(classOf[JUnitRunner])
class MyNumberTest extends FlatSpec with ShouldMatchers {
it should "post increment" in {
val x = new MyNumber(23)
val z = x++
z.number should equal (23)
x.number should equal (24)
}
// it should "pre increment" in {
// val x = new MyNumber(23)
// val z = ++x
//
// z.number should equal (24)
// x.number should equal (24)
// }
}