Part of mini-series of talks about gems in Scala standard library. Used for education of junior developers in our company. This pare is about Option, Either, Try and error handling in Scala in general.
Java is a mature programming language that is suitable to write reliable large programs. But Java hides also many traps. This talk summarizes experience from code quality review of a large enterprise application with over 1.5 million lines of code - problems and hidden bugs in code, and how to solve them.
Java is a mature programming language that is suitable to write reliable large programs. But Java hides also many traps. This talk summarizes experience from code quality review of a large enterprise application with over 1.5 million lines of code - problems and hidden bugs in code, and how to solve them.
Se puede encontrar en:
https://github.com/jksrecko/libaria/blob/master/examples/directMotionExample.cpp
Agradesco a la persona que compartio este codigo ya que muestra una idea general de lo que se puede hacer con el robot AmigoBot
jksrecko
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. The purpose of this webinar is to talk about some Do's and Don'ts of Java programming.
The webinar will cover the following areas:
- Top 10 mistakes made by Java programmers – How to avoid them
- Core Java- Best Practices – This covers good and bad practices both
- How to prepare for Java Interviews and Sun Java Exams
- Q&A
Key learnings from this webinar:
- It will benefit both junior and senior java professionals so that they don’t make common errors
- Clarity of concepts of Java
- Better awareness of best practices of Java
This talk presents the Erjang project, where Trifork is building a JVM-based Erlang VM.
The first half of the presentation is about lessons learned doing the project, the second half is more technical about Erjang's implementation.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
Se puede encontrar en:
https://github.com/jksrecko/libaria/blob/master/examples/directMotionExample.cpp
Agradesco a la persona que compartio este codigo ya que muestra una idea general de lo que se puede hacer con el robot AmigoBot
jksrecko
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
We have this new language, Swift, which takes some familiar Apple patterns, and introduces some new ones. With tools like closures and method chaining, there are definitely some new ways to solve the age-old Obj-c architecture challenges. This talk will walk through some of the most common Obj-c design patterns rewritten in Swift, and showcase the strengths and weaknesses of this new language.
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
Whether you program regularly in Java, and know it like the back of your hand, or whether you’re new to the language or a casual programmer, you’ll make mistakes. The purpose of this webinar is to talk about some Do's and Don'ts of Java programming.
The webinar will cover the following areas:
- Top 10 mistakes made by Java programmers – How to avoid them
- Core Java- Best Practices – This covers good and bad practices both
- How to prepare for Java Interviews and Sun Java Exams
- Q&A
Key learnings from this webinar:
- It will benefit both junior and senior java professionals so that they don’t make common errors
- Clarity of concepts of Java
- Better awareness of best practices of Java
This talk presents the Erjang project, where Trifork is building a JVM-based Erlang VM.
The first half of the presentation is about lessons learned doing the project, the second half is more technical about Erjang's implementation.
Composing an App with Free Monads (using Cats)Hermann Hueck
In this talk I will explain what Free Monads are and how to use them (using the Cats implementation).
After having shown the basics I build a small app by composing several
Free Monads to a small program.
I discuss the pros and cons of this technique.
Finally I will demonstrate how to avoid some boilerplate with the FreeK library.
Function Programming in Scala.
A lot of my examples here comes from the book
Functional programming in Scala By Paul Chiusano and Rúnar Bjarnason, It is a good book, buy it.
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/
Are you stuck in the Java world? I’ll share my story about convincing my team and the client of the benefits of Kotlin. Furthermore I’ll delve into how we migrated an existing Java Android app, with 300k active users, to Kotlin.
Even if you have never seen Kotlin before, come and see how you will create better apps with this modern and elegant language. At the end of this talk you’ll be able to convince your team / client why it’s a great to use Kotlin.
The power of Kotlin can be leveraged everywhere you use Java, since it compiles to JVM bytecode. So even if you’re not an Android developer, check out this session to get acquainted with Kotlin!
No excuses: switch to Kotlin
Ever wonder what this "new" Kotlin thing is? Curious what the syntax looks like? Unsure how to implement this at your own company? Or do you just want to know what Nick and Cody's favorite things are about this language?
All that and (maybe) more are revealed in Privet Kotlin.
Esoft Metro Campus - Diploma in Information Technology - (Module VIII) Programming with Java
(Template - Virtusa Corporate)
Contents:
Introduction to Java
Features of Java
What you can create by Java?
Start Java Programming
Creating First Java Program
Java Virtual Machine
Basic Rules to Remember
Keywords in Java
Comments in Java Programs
Printing Statements
Primitive Data Types in Java
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
If Statement
If… Else Statement
If… Else if… Else Statement
Nested If Statement
While Loop
Do While Loop
For Loop
Reading User Input
Arrays
Two Dimensional Arrays
Objects and Classes
Java Classes
Java Objects
Methods with Return Value
Methods without Return Value
Method Overloading
Variable Types
Inheritance
Method Overriding
Access Modifiers
Packages
GUI Applications in Java
Java Applets
Android & Kotlin - The code awakens #03Omar Miatello
A series of 3 events for building apps with Kotlin on Android.
Introduction to Kotlin, a modern language, developed by JetBrains (those who developed the IDE on which is based Android Studio) that compared to Java is more concise, versatile and with better error handling. The code is 100% interoperable with Java, and can be used to write native Android apps or small component.
How to apply functional concepts in modeling domain objects. Examples are in Scala. Presented on Rubyslava / PyVo #32 (see http://lanyrd.com/2013/rubyslava-september)
An introduction to SBT and how it works internally.
Talk from September 2013 Slovak Scala User Group meet-up, http://www.meetup.com/slovak-scala/events/133327122/
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Overview on Edible Vaccine: Pros & Cons with Mechanism
Option, Either, Try and what to do with corner cases when they arise
1. OPTION, EITHER, TRY
AND WHAT TO DO WITH CORNER CASES WHEN
THEY ARISE
KNOW YOUR LIBRARY MINI-SERIES
By /Michal Bigos @teliatko
2. KNOW YOUR LIBRARY - MINI SERIES
1. Hands-on with types from Scala library
2. DO's and DON'Ts
3. Intended for rookies, but Scala basic syntax assumed
4. Real world use cases
3. WHY NULL ISN'T AN OPTION
CONSIDER FOLLOWING CODE
String foo = request.params("foo")
if (foo != null) {
String bar = request.params("bar")
if (bar != null) {
doSomething(foo, bar)
} else {
throw new ApplicationException("Bar not found")
}
} else {
throw new ApplicationException("Foo not found")
}
4. WHY NULL ISN'T AN OPTION
WHAT'S WRONG WITH NULL
/* 1. Nobody knows about null, not even compiler */
String foo = request.params("foo")
/* 2. Annoying checking */
if (foo != null) {
String bar = request.params("bar")
// if (bar != null) {
/* 3. Danger of infamous NullPointerException,
everbody can forget some check */
doSomething(foo, bar)
// } else {
/* 4. Optionated detailed failures,
sometimes failure in the end is enough */
// throw new ApplicationException("Bar not found")
// }
} else {
/* 5. Design flaw, just original exception replacement */
throw new ApplicationException("Foo not found")
}
5. DEALING WITH NON-EXISTENCE
DIFFERENT APPROACHES COMPARED
Java relies on sad null
Groovy provides null-safe operator for accessing
properties
Clojure uses nilwhich is okay very often, but sometimes
it leads to an exception higher in call hierarchy
foo?.bar?.baz
6. GETTING RID OF NULL
NON-EXISTENCE SCALA WAY
Container with one or none element
sealed abstract class Option[A]
case class Some[+A](x: A) extends Option[A]
case object None extends Option[Nothing]
7. OPTION
1. States that value may or may not be present on type level
2. You are forced by the compiler to deal with it
3. No way to accidentally rely on presence of a value
4. Clearly documents an intention
9. OPTION
CREATING AN OPTION
Never do this
Rather use factory method on companion object
val certain = Some("Sun comes up")
val pitty = None
val nonSense = Some(null)
val muchBetter = Option(null) // Results to None
val certainAgain = Option("Sun comes up") // Some(Sun comes up)
10. OPTION
WORKING WITH OPTION AN OLD WAY
Don't do this (only in exceptional cases)
// Assume that
def param[String](name: String): Option[String] ...
val fooParam = request.param("foo")
val foo = if (fooParam.isDefined) {
fooParam.get // throws NoSuchElementException when None
} else {
"Default foo" // Default value
}
11. OPTION
PATTERN MATCHING
Don't do this (there's a better way)
val foo = request.param("foo") match {
case Some(value) => value
case None => "Default foo" // Default value
}
12. OPTION
PROVIDING A DEFAULT VALUE
Default value is by-name parameter. It's evaluated lazily.
// any long computation for default value
val foo = request.param("foo") getOrElse ("Default foo")
13. OPTION
TREATING IT FUNCTIONAL WAY
Think of Option as collection
It is biased towards Some
You can map, flatMapor compose Option(s) when it
contains value, i.e. it's Some
14. OPTION
EXAMPLE
Suppose following model and DAO
case class User(id: Int, name: String, age: Option[Int])
// In domain model, any optional value has to be expressed with Option
object UserDao {
def findById(id: Int): Option[User] = ...
// Id can always be incorrect, e.g. it's possible that user does not
exist already
}
15. OPTION
SIDE-EFFECTING
Use case: Printing the user name
// Suppose we have an userId from somewhere
val userOpt = UserDao.findById(userId)
// Just print user name
userOpt.foreach { user =>
println(user.name) // Nothing will be printed when None
} // Result is Unit (like void in Java)
// Or more concise
userOpt.foreach( user => println(user) )
// Or even more
userOpt.foreach( println(_) )
userOpt.foreach( println )
16. OPTION
MAP, FLATMAP & CO.
Use case: Extracting age
// Extracting age
val ageOpt = UserDao.findById(userId).map( _.age )
// Returns Option[Option[Int]]
val ageOpt = UserDao.findById(userId).map( _.age.map( age => age ) )
// ReturnsOption[Option[Int]] too
// Extracting age, take 2
val ageOpt = UserDao.findById(userId).flatMap( _.age.map( age => age )
)
// Returns Option[Int]
17. OPTION
FOR COMPREHENSIONS
Same use case as before
Usage in left side of generator
// Extracting age, take 3
val ageOpt = for {
user <- UserDao.findById(userId)
age <- user.age
} yield age // Returns Option[Int]
// Extracting age, take 3
val ageOpt = for {
User(_, Some(age)) <- UserDao.findById(userId)
} yield age // Returns Option[Int]
18. OPTION
COMPOSING TO LIST
Use case: Pretty-print of user
Different notation
Both prints
Rule of thumb: wrap all mandatory fields with Option and
then concatenate with optional ones
def prettyPrint(user: User) =
List(Option(user.name), user.age).mkString(", ")
def prettyPrint(user: User) =
(Option(user.name) ++ user.age).mkString(", ")
val foo = User("Foo", Some(10))
val bar = User("Bar", None)
prettyPrint(foo) // Prints "Foo, 10"
prettyPrint(bar) // Prints "Bar"
19.
20. OPTION
CHAINING
Use case: Fetching or creating the user
More appropriate, when Useris desired directly
object UserDao {
// New method
def createUser: User
}
val userOpt = UserDao.findById(userId) orElse Some(UserDao.create)
val user = UserDao.findById(userId) getOrElse UserDao.create
21. OPTION
MORE TO EXPLORE
sealed abstract class Option[A] {
def fold[B](ifEmpty: Ó B)(f: (A) Ó B): B
def filter(p: (A) Ó Boolean): Option[A]
def exists(p: (A) Ó Boolean): Boolean
...
}
22. IS OPTION APPROPRIATE?
Consider following piece of code
When something went wrong, cause is lost forever
case class UserFilter(name: String, age: Int)
def parseFilter(input: String): Option[UserFilter] = {
for {
name <- parseName(input)
age <- parseAge(input)
} yield UserFilter(name, age)
}
// Suppose that parseName and parseAge throws FilterException
def parseFilter(input: String): Option[UserFilter]
throws FilterException { ... }
// caller side
val filter = try {
parseFilter(input)
} catch {
case e: FilterException => whatToDoInTheMiddleOfTheCode(e)
}
24. INTRODUCING EITHER
Container with disjoint types.
sealed abstract class Either[+L, +R]
case class Left[+L, +R](a: L) extends Either[L, R]
case class Right[+L, +R](b: R) extends Either[L, R]
25. EITHER
1. States that value is either Left[L]or Right[R], but
never both.
2. No explicit sematics, but by convention Left[L]
represents corner case and Right[R]desired one.
3. Functional way of dealing with alternatives, consider:
4. Again, it clearly documents an intention
def doSomething(): Int throws SomeException
// what is this saying? two possible outcomes
def doSomething(): Either[SomeException, Int]
// more functional only one return value
27. EITHER
CREATING EITHER
There is no Either(...)factory method on companion
object.
def parseAge(input: String): Either[String, Int] = {
try {
Right(input.toInt)
} catch {
case nfe: NumberFormatException => Left("Unable to parse age")
}
}
28. EITHER
WORKING AN OLD WAY AGAIN
Don't do this (only in exceptional cases)
def parseFilter(input: String): Either[String, ExtendedFilter] = {
val name = parseName(input)
if (name.isRight) {
val age = parseAge(input)
if (age.isRight) {
Right(UserFilter(time, rating))
} else age
} else name
}
29. EITHER
PATTERN MATCHING
Don't do this (there's a better way)
def parseFilter(input: String): Either[String, ExtendedFilter] = {
parseName(input) match {
case Right(name) => parseAge(input) match {
case Right(age) => UserFilter(name, age)
case error: Left[_] => error
}
case error: Left[_] => error
}
}
30. EITHER
PROJECTIONS
You cannot directly use instance of Eitheras collection.
It's unbiased, you have to define what is your prefered side.
Working on success, only 1st error is returned.
either.rightreturns RightProjection
def parseFilter(input: String): Either[String, UserFilter] = {
for {
name <- parseName(input).right
age <- parseAge(input).right
} yield Right(UserFilter(name, age))
}
31. EITHER
PROJECTIONS, TAKE 2
Working on both sides, all errors are collected.
either.leftreturns LeftProjection
def parseFilter(input: String): Either[List[String], UserFilter] = {
val name = parseName(input)
val age = parseAge(input)
val errors = name.left.toOption ++ age.left.toOption
if (errors.isEmpty) {
Right(UserFilter(name.right.get, age.right.get))
} else {
Left(errors)
}
}
32. EITHER
PROJECTIONS, TAKE 3
Both projection are biased wrappers for Either
You can use map, flatMapon them too, but beware
This is inconsistent in regdard to other collections.
val rightThing = Right(User("Foo", Some(10)))
val projection = rightThing.right // Type is RightProjection[User]
val rightThingAgain = projection.map ( _.name )
// Isn't RightProjection[User] but Right[User]
33. EITHER
PROJECTIONS, TAKE 4
It can lead to problems with for comprehensions.
This won't compile.
After removing syntactic suggar, we get
We need projection again
for {
name <- parseName(input).right
bigName <- name.capitalize
} yield bigName
parseName(input).right.map { name =>
val bigName = name.capitalize
(bigName)
}.map { case (x) => x } // Map is not member of Either
34. for {
name <- parseName(input).right
bigName <- Right(name.capitalize).right
} yield bigName
35. EITHER
FOLDING
Allows transforming the Eitherregardless if it's Rightor
Lefton the same type
Accepts functions, both are evaluated lazily. Result from both
functions has same type.
// Once upon a time in controller
parseFilter(input).fold(
// Bad (Left) side transformation to HttpResponse
errors => BadRequest("Error in filter")
// Good (Right) side transformation to HttpResponse
filter => Ok(doSomethingWith(filter))
)
36. EITHER
MORE TO EXPLORE
sealed abstract class Either[+A, +B] {
def joinLeft[A1 >: A, B1 >: B, C](implicit ev: <:<[A1, Either[C, B1
]]): Either[C, B1]
def joinRight[A1 >: A, B1 >: B, C](implicit ev: <:<[B1, Either[A1,
C]]): Either[A1, C]
def swap: Product with Serializable with Either[B, A]
}
37. THROWING AND CATCHING EXCEPTIONS
SOMETIMES THINGS REALLY GO WRONG
You can use classic try/catch/finallyconstruct
def parseAge(input: String): Either[String, Int] = {
try {
Right(input.toInt)
} catch {
case nfe: NumberFormatException => Left("Unable to parse age")
}
}
38. THROWING AND CATCHING EXCEPTIONS
SOMETIMES THINGS REALLY GO WRONG, TAKE 2
But, it's try/catch/finallyon steroids thanks to pattern
matching
try {
someHorribleCodeHere()
} catch {
// Catching multiple types
case e @ (_: IOException | _: NastyExpception) => cleanUpMess()
// Catching exceptions by message
case e : AnotherNastyException
if e.getMessage contains "Wrong again" => cleanUpMess()
// Catching all exceptions
case e: Exception => cleanUpMess()
}
39. THROWING AND CATCHING EXCEPTIONS
SOMETIMES THINGS REALLY GO WRONG, TAKE 3
It's powerful, but beware
Never do this!
Prefered approach of catching all
try {
someHorribleCodeHere()
} catch {
// This will match scala.util.control.ControlThrowable too
case _ => cleanUpMess()
}
try {
someHorribleCodeHere()
} catch {
// This will match scala.util.control.ControlThrowable too
case t: ControlThrowable => throw t
case _ => cleanUpMess()
}
40.
41. WHAT'S WRONG WITH EXCEPTIONS
1. Referential transparency - is there a value the RHS can be
replaced with? No.
2. Code base can become ugly
3. Exceptions do not go well with concurrency
val something = throw new IllegalArgumentException("Foo is missing")
// Result type is Nothing
42. SHOULD I THROW AN EXCEPTION?
No, there is better approach
43. EXCEPTION HANDLING FUNCTIONAL WAY
Please welcome
import scala.util.control._
and
Collection of Throwableor value
sealed trait Try[A]
case class Failure[A](e: Throwable) extends Try[A]
case class Success[A](value: A) extends Try[A]
44. TRY
1. States that computation may be Success[T]or may be
Failure[T]ending with Throwableon type level
2. Similar to Option, it's Successbiased
3. It's try/catchwithout boilerplate
4. Again it clearly documents what is happening
45. TRY
LIKE OPTION
All the operations from Optionare present
sealed abstract class Try[+T] {
// Throws exception of Failure or return value of Success
def get: T
// Old way checks
def isFailure: Boolean
def isSuccess: Boolean
// map, flatMap & Co.
def map[U](f: (T) Ó U): Try[U]
def flatMap[U](f: (T) Ó Try[U]): Try[U]
// Side effecting
def foreach[U](f: (T) Ó U): Unit
// Default value
def getOrElse[U >: T](default: Ó U): U
// Chaining
def orElse[U >: T](default: Ó Try[U]): Try[U]
}
46. TRY
BUT THERE IS MORE
Assume that
Recovering from a Failure
Converting to Option
def parseAge(input: String): Try[Int] = Try ( input.toInt )
val age = parseAge("not a number") recover {
case e: NumberFormatException => 0 // Default value
case _ => -1 // Another default value
} // Result is always Success
val ageOpt = age.toOption
// Will be Some if Success, None if Failure