DynamicVariables
provide a binding mechanism where the current
value is found through dynamic scope, but where access to the
variable itself is resolved through static scope.
Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of scala.util.Left or scala.util.Right.
Represents a value of one of two possible types (a disjoint union.) Instances of Either are either an instance of scala.util.Left or scala.util.Right.
A common use of Either is as an alternative to scala.Option for dealing with possible missing values. In this usage, scala.None is replaced with a scala.util.Left which can contain useful information. scala.util.Right takes the place of scala.Some. Convention dictates that Left is used for failure and Right is used for success.
For example, you could use Either[String, Int]
to detect whether a
received input is a String or an Int.
val in = Console.readLine("Type Either a string or an Int: ") val result: Either[String,Int] = try { Right(in.toInt) } catch { case e: Exception => Left(in) } println( result match { case Right(x) => "You passed me the Int: " + x + ", which I will increment. " + x + " + 1 = " + (x+1) case Left(x) => "You passed me the String: " + x })
A projection can be used to selectively operate on a value of type Either,
depending on whether it is of type Left or Right. For example, to transform an
Either using a function, in the case where it's a Left, one can first apply
the left
projection and invoke map
on that projected Either. If a right
projection is applied to that Left, the original Left is returned, unmodified.
val l: Either[String, Int] = Left("flower") val r: Either[String, Int] = Right(12) l.left.map(_.size): Either[Int, Int] // Left(6) r.left.map(_.size): Either[Int, Int] // Right(12) l.right.map(_.toDouble): Either[String, Double] // Left("flower") r.right.map(_.toDouble): Either[String, Double] // Right(12.0)
Like with other types which define a map
method, the same can be achieved
using a for-comprehension:
for (s <- l.left) yield s.size // Left(6)
You may also bias Either
values,
decorating them so they can be operated upon and used in for comprehensions without
extracting projections. If we treat Either
as analogous to Option
, a right-biased Either
treats Right
instances as
good values while Left
instances represent failures, more descriptive variations on None
.
(Either
can also be left-biased, but right-biasing is conventional and should
be preferred.)
Biased Either
values support pattern matches, variable assignments, and
conditionals in for comprehensions, which left- and right-projections do not.
You can right-bias Either
very simply via the following import statement:
import Either.RightBias._ val a : Either[String,Int] = Right(1) val b : Either[String,Int] = Right(99) for( v <- a; w <- b ) yield v+w // Right(100) for( v <- a; w <- b if v > 10) yield v+w // throws NoSuchElementException
In order to support filter operations without throwing an Exception upon failure, a right bias may define a left-side token to indicate emptiness.
val RightBias = Either.RightBias.withEmptyToken[String]("EMPTY") import RightBias._ val a : Either[String,Int] = Right(1) val b : Either[String,Int] = Right(99) for( v <- a; w <- b ) yield v+w // Right(100) for( v <- a; w <- b if v > 10) yield v+w // Left(EMPTY)
For very extensive documentation of biased Either
, please see RightBias
(or, if you wish to defy convention, LeftBias).
For documentation of operations supported by biased Either
values, see right-biased ops / left-biased ops.
1.0, 11/10/2008
2.7
The left side of the disjoint union, as opposed to the scala.util.Right side.
The left side of the disjoint union, as opposed to the scala.util.Right side.
1.0, 11/10/2008
The right side of the disjoint union, as opposed to the scala.util.Left side.
The right side of the disjoint union, as opposed to the scala.util.Left side.
1.0, 11/10/2008
The Try
type represents a computation that may either result in an exception, or return a
successfully computed value.
The Try
type represents a computation that may either result in an exception, or return a
successfully computed value. It's similar to, but semantically different from the scala.util.Either type.
Instances of Try[T]
, are either an instance of scala.util.Success[T] or scala.util.Failure[T].
For example, Try
can be used to perform division on a user-defined input, without the need to do explicit
exception-handling in all of the places that an exception might occur.
Example:
import scala.util.{Try, Success, Failure} def divide: Try[Int] = { val dividend = Try(Console.readLine("Enter an Int that you'd like to divide:\n").toInt) val divisor = Try(Console.readLine("Enter an Int that you'd like to divide by:\n").toInt) val problem = dividend.flatMap(x => divisor.map(y => x/y)) problem match { case Success(v) => println("Result of " + dividend.get + "/"+ divisor.get +" is: " + v) Success(v) case Failure(e) => println("You must've divided by zero or entered something that's not an Int. Try again!") println("Info from the exception: " + e.getMessage) divide } }
An important property of Try
shown in the above example is its ability to pipeline, or chain, operations,
catching exceptions along the way. The flatMap
and map
combinators in the above example each essentially
pass off either their successfully completed value, wrapped in the Success
type for it to be further operated
upon by the next combinator in the chain, or the exception wrapped in the Failure
type usually to be simply
passed on down the chain. Combinators such as rescue
and recover
are designed to provide some type of
default behavior in the case of failure.
Note: only non-fatal exceptions are caught by the combinators on Try
(see scala.util.control.NonFatal).
Serious system errors, on the other hand, will be thrown.
Note:: all Try combinators will catch exceptions and return failure unless otherwise specified in the documentation.
Try
comes to the Scala standard library after years of use as an integral part of Twitter's stack.
2.10
A class designed to generate well-distributed non-cryptographic hashes.
A class designed to generate well-distributed non-cryptographic hashes. It is designed to be passed to a collection's foreach method, or can take individual hash values with append. Its own hash code is set equal to the hash code of whatever it is hashing.
(Since version 2.10.0) Use the object MurmurHash3 instead.
Loads library.properties
from the jar.
The object Random
offers a default implementation
of scala.util.Random and random-related convenience methods.
The object Random
offers a default implementation
of scala.util.Random and random-related convenience methods.
2.8
The Sorting object provides functions that can sort various kinds of objects.
The Sorting object provides functions that can sort various kinds of objects. You can provide a comparison function, or you can request a sort of items that are viewable as scala.math.Ordered. Some sorts that operate directly on a subset of value types are also provided. These implementations are derived from those in the Sun JDK.
Note that stability doesn't matter for value types, so use the quickSort
variants for those. stableSort
is intended to be used with
objects when the prior ordering should be preserved, where possible.
1.0
An object designed to generate well-distributed non-cryptographic hashes.
An object designed to generate well-distributed non-cryptographic hashes. It is designed to hash a collection of integers; along with the integers to hash, it generates two magic streams of integers to increase the distribution of repetitive input sequences. Thus, three methods need to be called at each step (to start and to incorporate a new integer) to update the values. Only one method needs to be called to finalize the hash.
(Since version 2.10.0) Use the object MurmurHash3 instead.
DynamicVariables
provide a binding mechanism where the current value is found through dynamic scope, but where access to the variable itself is resolved through static scope.The current value can be retrieved with the value method. New values should be pushed using the
withValue
method. Values pushed viawithValue
only stay valid while thewithValue
's second argument, a parameterless closure, executes. When the second argument finishes, the variable reverts to the previous value.Each thread gets its own stack of bindings. When a new thread is created, the
DynamicVariable
gets a copy of the stack of bindings from the parent thread, and from then on the bindings for the new thread are independent of those for the original thread.1.1, 2007-5-21