Movatterモバイル変換


[0]ホーム

URL:


Scala 3
3.7.4
LearnInstallPlaygroundFind A LibraryCommunityBlog
Scala 3
LearnInstallPlaygroundFind A LibraryCommunityBlog
DocsAPI
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL
Scala 3/scala/scala.util

scala.util

packagescala.util

Members list

Type members

Classlikes

finalclassChainingOps[A](self:A) extendsAnyVal

Adds chaining methodstap andpipe to every type.

Adds chaining methodstap andpipe to every type.

Attributes

Source
ChainingOps.scala
Supertypes
classAnyVal
traitMatchable
classAny

Attributes

Source
ChainingOps.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
objectchaining

A utility object to support command line parsing for @main methods

A utility object to support command line parsing for @main methods

Attributes

Source
CommandLineParser.scala
Supertypes
classObject
traitMatchable
classAny
Self type
classDynamicVariable[T](init:T)

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.

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 thewithValue 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.

someDynamicVariable.withValue(newValue) {  // ... code called in here that calls value ...  // ... will be given back the newValue ...}

Each thread gets its own stack of bindings. When a new thread is created, theDynamicVariable 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.

Attributes

Source
DynamicVariable.scala
Supertypes
classObject
traitMatchable
classAny
sealed abstractclassEither[+A,+B] extendsProduct,Serializable

Represents a value of one of two possible types (a disjoint union).

Represents a value of one of two possible types (a disjoint union). An instance ofEither is an instance of eitherscala.util.Left orscala.util.Right.

A common use ofEither is as an alternative toscala.Option for dealing with possibly missing values. In this usage,scala.None is replaced with ascala.util.Left which can contain useful information.scala.util.Right takes the place ofscala.Some. Convention dictates thatLeft is used for failure andRight is used for success.

For example, you could useEither[String, Int] to indicate whether a received input is aString or anInt.

import scala.io.StdIn._val in = readLine("Type Either a string or an Int: ")val result: Either[String,Int] =  try Right(in.toInt)  catch {    case e: NumberFormatException => Left(in)  }result match {  case Right(x) => s"You passed me the Int: $x, which I will increment. $x + 1 = ${x+1}"  case Left(x)  => s"You passed me the String: $x"}

Either is right-biased, which means thatRight is assumed to be the default case to operate on. If it isLeft, operations likemap andflatMap return theLeft value unchanged:

def doubled(i: Int) = i * 2Right(42).map(doubled) // Right(84)Left(42).map(doubled)  // Left(42)

SinceEither defines the methodsmap andflatMap, it can also be used in for comprehensions:

val right1 = Right(1)   : Right[Double, Int]val right2 = Right(2)val right3 = Right(3)val left23 = Left(23.0) : Left[Double, Int]val left42 = Left(42.0)for {  x <- right1  y <- right2  z <- right3} yield x + y + z // Right(6)for {  x <- right1  y <- right2  z <- left23} yield x + y + z // Left(23.0)for {  x <- right1  y <- left23  z <- right2} yield x + y + z // Left(23.0)// Guard expressions are not supported:for {  i <- right1  if i > 0} yield i// error: value withFilter is not a member of Right[Double,Int]// Similarly, refutable patterns are not supported:for (x: Int <- right1) yield x// error: value withFilter is not a member of Right[Double,Int]// To use a filtered value, convert to an Option first,// which drops the Left case, as None contains no value:for {  i <- right1.toOption  if i > 0} yield i

Sincefor comprehensions usemap andflatMap, the types of function parameters used in the expression must be inferred. These types are constrained by theEither values. In particular, because of right-biasing,Left values may require an explicit type argument for type parameterB, the right value. Otherwise, it might be inferred asNothing.

for {  x <- left23  y <- right1  z <- left42  // type at this position: Either[Double, Nothing]} yield x + y + z//            ^// error: ambiguous reference to overloaded definition,// both method + in class Int of type (x: Char)Int// and  method + in class Int of type (x: Byte)Int// match argument types (Nothing)for (x <- right2 ; y <- left23) yield x + y  // Left(23.0)for (x <- right2 ; y <- left42) yield x + y  // errorfor {  x <- right1  y <- left42  // type at this position: Either[Double, Nothing]  z <- left23} yield x + y + z// Left(42.0), but unexpectedly a `Either[Double,String]`

Attributes

Companion
object
Source
Either.scala
Supertypes
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
Known subtypes
classLeft[A,B]
classRight[A,B]
objectEither

Attributes

Companion
class
Source
Either.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Either.type
final caseclassFailure[+T](exception:Throwable) extendsTry[T]

Attributes

Source
Try.scala
Supertypes
classTry[T]
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
traitFromDigits[T]

A type class for types that admit numeric literals.

A type class for types that admit numeric literals.

Attributes

Companion
object
Source
FromDigits.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
traitDecimal[T]
traitFloating[T]
traitWithRadix[T]

Attributes

Companion
trait
Source
FromDigits.scala
Supertypes
classObject
traitMatchable
classAny
Self type
final caseclassLeft[+A,+B](value:A) extendsEither[A,B]

The left side of the disjoint union, as opposed to thescala.util.Right side.

The left side of the disjoint union, as opposed to thescala.util.Right side.

Attributes

Source
Either.scala
Supertypes
classEither[A,B]
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all

Attributes

Source
NotGiven.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
objectNotGiven
finalclassNotGiven[+T]

A special class used to implement negation in implicit search.

A special class used to implement negation in implicit search.

Consider the problem of using impliciti1 for a query typeD if an implicit for some other classC is available, and using an impliciti2 if no implicit value of typeC is available. If we do not want to prioritizei1 andi2 by putting them in different traits we can instead define the following:

given i1: D(using ev: C) = ... given i2: D(using ev: NotGiven[C]) = ...

NotGiven is treated specially in implicit search, similar to the way logical negation is treated in Prolog: The implicit search forNotGiven[C] succeeds if and only if the implicit search forC fails.

In Scala 2 this form of negation can be simulated by setting up a conditional ambiguous implicit and an unconditional fallback, the way it is done with thedefault,amb1 andamb2 methods below. Due to the way these two methods are defined,NotGiven is also usable from Scala 2.

In Dotty, ambiguity is a global error, and therefore cannot be used to implement negation. Instead,NotGiven is treated natively in implicit search.

Attributes

Companion
object
Source
NotGiven.scala
Supertypes
classObject
traitMatchable
classAny

Attributes

Companion
class
Source
NotGiven.scala
Supertypes
Self type

Loadslibrary.properties from the jar.

Loadslibrary.properties from the jar.

Attributes

Source
Properties.scala
Supertypes
classObject
traitMatchable
classAny
Self type
classRandom(valself:Random) extendsSerializable

Attributes

Companion
object
Source
Random.scala
Supertypes
classObject
traitMatchable
classAny
Known subtypes
objectRandom
objectRandom extendsRandom

The objectRandom offers a default implementation of scala.util.Random and random-related convenience methods.

The objectRandom offers a default implementation of scala.util.Random and random-related convenience methods.

Attributes

Companion
class
Source
Random.scala
Supertypes
classRandom
classObject
traitMatchable
classAny
Self type
Random.type
final caseclassRight[+A,+B](value:B) extendsEither[A,B]

The right side of the disjoint union, as opposed to thescala.util.Left side.

The right side of the disjoint union, as opposed to thescala.util.Left side.

Attributes

Source
Either.scala
Supertypes
classEither[A,B]
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
objectSorting

TheSorting object provides convenience wrappers forjava.util.Arrays.sort.

TheSorting object provides convenience wrappers forjava.util.Arrays.sort. Methods that defer tojava.util.Arrays.sort say that they do or under what conditions that they do.

Sorting also implements a general-purpose quicksort and stable (merge) sort for those cases wherejava.util.Arrays.sort could only be used at the cost of a large memory penalty. If performance rather than memory usage is the primary concern, one may wish to find alternate strategies to usejava.util.Arrays.sort directly e.g. by boxing primitives to use a custom ordering on them.

Sorting provides methods where you can provide a comparison function, or can request a sort of items that arescala.math.Ordered or that otherwise have an implicit or explicitscala.math.Ordering.

Note also that high-performance non-default sorts for numeric types are not provided. If this is required, it is advisable to investigate other libraries that cover this use case.

Attributes

Source
Sorting.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Sorting.type
final caseclassSuccess[+T](value:T) extendsTry[T]

Attributes

Source
Try.scala
Supertypes
classTry[T]
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
sealed abstractclassTry[+T] extendsProduct,Serializable

TheTry type represents a computation that may fail during evaluation by raising an exception.

TheTry type represents a computation that may fail during evaluation by raising an exception. It holds either a successfully computed value or the exception that was thrown. This is similar to thescala.util.Either type, but with different semantics.

Instances ofTry[T] are an instance of eitherscala.util.Success[T] orscala.util.Failure[T].

For example, consider a computation that performs division on user-defined input.Try can reduce or eliminate the need for explicit exception handling in all of the places where an exception might be thrown.

Example:

import scala.io.StdInimport scala.util.{Try, Success, Failure}def divide: Try[Int] = {  val dividend = Try(StdIn.readLine("Enter an Int that you'd like to divide:\n").toInt)  val divisor = Try(StdIn.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 ofTry shown in the above example is its ability topipeline, or chain, operations, catching exceptions along the way. TheflatMap andmap combinators in the above example each essentially pass off either their successfully completed value, wrapped in theSuccess type for it to be further operated upon by the next combinator in the chain, or the exception wrapped in theFailure type usually to be simply passed on down the chain. Combinators such asrecover andrecoverWith are designed to provide some type of default behavior in the case of failure.

Note: only non-fatal exceptions are caught by the combinators onTry (seescala.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.

Attributes

Companion
object
Source
Try.scala
Supertypes
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
Known subtypes
classFailure[T]
classSuccess[T]
objectTry

Attributes

Companion
class
Source
Try.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Try.type
objectUsing

A utility for performing automatic resource management.

A utility for performing automatic resource management. It can be used to perform an operation using resources, after which it releases the resources in reverse order of their creation.

Usage

There are multiple ways to automatically manage resources withUsing. If you only need to manage a single resource, theapply method is easiest; it wraps the resource opening, operation, and resource releasing in aTry.

Example:

import java.io.{BufferedReader, FileReader}import scala.util.{Try, Using}val lines: Try[Seq[String]] = Using(new BufferedReader(new FileReader("file.txt"))) { reader =>   Iterator.continually(reader.readLine()).takeWhile(_ != null).toSeq }

If you need to manage multiple resources,Using.Manager should be used. It allows the managing of arbitrarily many resources, whose creation, use, and release are all wrapped in aTry.

Example:

import java.io.{BufferedReader, FileReader}import scala.util.{Try, Using}val files = List("file1.txt", "file2.txt", "file3.txt", "file4.txt")val lines: Try[Seq[String]] = Using.Manager { use => // acquire resources def mkreader(filename: String) = use(new BufferedReader(new FileReader(filename))) // use your resources here def lines(reader: BufferedReader): Iterator[String] =   Iterator.continually(reader.readLine()).takeWhile(_ != null) files.map(mkreader).flatMap(lines)}

Composed or "wrapped" resources may be acquired in order of construction, if "underlying" resources are not closed. Although redundant in this case, here is the previous example with a wrapped call touse:

def mkreader(filename: String) = use(new BufferedReader(use(new FileReader(filename))))

Custom resources can be registered on construction by requiring an implicitManager. This ensures they will be released even if composition fails:

import scala.util.Usingcase class X(x: String)(implicit mgr: Using.Manager) extends AutoCloseable { override def close() = println(s"CLOSE $x") mgr.acquire(this)}case class Y(y: String)(x: String)(implicit mgr: Using.Manager) extends AutoCloseable { val xres = X(x) override def close() = println(s"CLOSE $y") // an error during construction releases previously acquired resources require(y != null, "y is null") mgr.acquire(this)}Using.Manager { implicit mgr => val y = Y("Y")("X") println(s"USE $y")}println { Using.Manager { implicit mgr =>   Y(null)("X") }} // Failure(java.lang.IllegalArgumentException: requirement failed: y is null)

If you wish to avoid wrapping management and operations in aTry, you can useUsing.resource, which throws any exceptions that occur.

Example:

import java.io.{BufferedReader, FileReader}import scala.util.Usingval lines: Seq[String] = Using.resource(new BufferedReader(new FileReader("file.txt"))) { reader =>   Iterator.continually(reader.readLine()).takeWhile(_ != null).toSeq }

Suppression Behavior

If two exceptions are thrown (e.g., by an operation and closing a resource), one of them is re-thrown, and the other isadded to it as a suppressed exception. If the two exceptions are of different 'severities' (see below), the one of a higher severity is re-thrown, and the one of a lower severity is added to it as a suppressed exception. If the two exceptions are of the same severity, the one thrown first is re-thrown, and the one thrown second is added to it as a suppressed exception. If an exception is aControlThrowable, or if it does not support suppression (seeThrowable's constructor with anenableSuppression parameter), an exception that would have been suppressed is instead discarded.

Exceptions are ranked from highest to lowest severity as follows:

  • java.lang.VirtualMachineError

  • java.lang.LinkageError

  • java.lang.InterruptedException andjava.lang.ThreadDeath

  • fatal exceptions, excludingscala.util.control.ControlThrowable

  • scala.util.control.ControlThrowable

  • all other exceptions

When more than two exceptions are thrown, the first two are combined and re-thrown as described above, and each successive exception thrown is combined as it is thrown.

Attributes

Source
Using.scala
Supertypes
classObject
traitMatchable
classAny
Self type
Using.type
objectboundary

A boundary that can be exited bybreak calls.boundary andbreak represent a unified and superior alternative for thescala.util.control.NonLocalReturns andscala.util.control.Breaks APIs. The main differences are:

A boundary that can be exited bybreak calls.boundary andbreak represent a unified and superior alternative for thescala.util.control.NonLocalReturns andscala.util.control.Breaks APIs. The main differences are:

  • Unified names:boundary to establish a scope,break to leave it.break can optionally return a value.
  • Integration with exceptions.breaks are logically non-fatal exceptions. TheBreak exception class extendsRuntimeException and is optimized so that stack trace generation is suppressed.
  • Better performance: breaks to enclosing scopes in the same method can be rewritten to jumps.

Example usage:

import scala.util.boundary, boundary.breakdef firstIndex[T](xs: List[T], elem: T): Int = boundary:   for (x, i) <- xs.zipWithIndex do     if x == elem then break(i)   -1

Attributes

Source
boundary.scala
Supertypes
classObject
traitMatchable
classAny
Self type

Adds chaining methodstap andpipe to every type.

Adds chaining methodstap andpipe to every type. SeeChainingOps.

Attributes

Source
package.scala
Supertypes
classObject
traitMatchable
classAny
Self type

Experimental classlikes

sealedtraitTupledFunction[F,G]

Type class relating aFunctionN[..., R] with an equivalent tupled functionFunction1[TupleN[...], R]

Type class relating aFunctionN[..., R] with an equivalent tupled functionFunction1[TupleN[...], R]

Type parameters

F

a function type

G

a tupled function type (function of arity 1 receiving a tuple as argument)

Attributes

Experimental
true
Source
TupledFunction.scala
Supertypes
classObject
traitMatchable
classAny
In this article
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL

[8]ページ先頭

©2009-2025 Movatter.jp