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/Try

Try

scala.util.Try
See theTry companion object
sealed abstractclassTry[+T] extendsProduct,Serializable

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
Graph
Supertypes
traitProduct
traitEquals
classObject
traitMatchable
classAny
Show all
Known subtypes
classFailure[T]
classSuccess[T]

Members list

Type members

Classlikes

finalclassWithFilter(p:Try.this.T=>Boolean)

We need a whole WithFilter class to honor the "doesn't create a new collection" contract even though it seems unlikely to matter much in a collection with max size 1.

We need a whole WithFilter class to honor the "doesn't create a new collection" contract even though it seems unlikely to matter much in a collection with max size 1.

Attributes

Source
Try.scala
Supertypes
classObject
traitMatchable
classAny

Value members

Abstract methods

defcollect[U](pf:PartialFunction[T,U]):Try[U]

Applies the given partial function to the value from thisSuccess or returns this if this is aFailure.

Applies the given partial function to the value from thisSuccess or returns this if this is aFailure.

Attributes

Source
Try.scala

Inverts thisTry.

Inverts thisTry. If this is aFailure, returns its exception wrapped in aSuccess. If this is aSuccess, returns aFailure containing anUnsupportedOperationException.

Attributes

Source
Try.scala
deffilter(p:T=>Boolean):Try[T]

Converts this to aFailure if the predicate is not satisfied.

Converts this to aFailure if the predicate is not satisfied.

Attributes

Source
Try.scala
defflatMap[U](f:T=>Try[U]):Try[U]

Returns the given function applied to the value from thisSuccess or returns this if this is aFailure.

Returns the given function applied to the value from thisSuccess or returns this if this is aFailure.

Attributes

Source
Try.scala
defflatten[U](implicitev:T<:<Try[U]):Try[U]

Transforms a nestedTry, ie, aTry of typeTry[Try[T]], into an un-nestedTry, ie, aTry of typeTry[T].

Transforms a nestedTry, ie, aTry of typeTry[Try[T]], into an un-nestedTry, ie, aTry of typeTry[T].

Attributes

Source
Try.scala
deffold[U](fa:Throwable=>U,fb:T=>U):U

Appliesfa if this is aFailure orfb if this is aSuccess.

Appliesfa if this is aFailure orfb if this is aSuccess. Iffb is initially applied and throws an exception, thenfa is applied with this exception.

Value parameters

fa

the function to apply if this is aFailure

fb

the function to apply if this is aSuccess

Attributes

Returns

the results of applying the function

Example

val result: Try[Int] = Try { string.toInt }log(result.fold( ex => "Operation failed with " + ex, v => "Operation produced value: " + v))
Source
Try.scala
defforeach[U](f:T=>U):Unit

Applies the given functionf if this is aSuccess, otherwise returnsUnit if this is aFailure.

Applies the given functionf if this is aSuccess, otherwise returnsUnit if this is aFailure.

Note: Iff throws, then this method may throw an exception.

Attributes

Source
Try.scala
defget:T

Returns the value from thisSuccess or throws the exception if this is aFailure.

Returns the value from thisSuccess or throws the exception if this is aFailure.

Attributes

Source
Try.scala
defgetOrElse[U >:T](default:=>U):U

Returns the value from thisSuccess or the givendefault argument if this is aFailure.

Returns the value from thisSuccess or the givendefault argument if this is aFailure.

Note:: This will throw an exception if it is not a success and default throws an exception.

Attributes

Source
Try.scala

Returnstrue if theTry is aFailure,false otherwise.

Returnstrue if theTry is aFailure,false otherwise.

Attributes

Source
Try.scala

Returnstrue if theTry is aSuccess,false otherwise.

Returnstrue if theTry is aSuccess,false otherwise.

Attributes

Source
Try.scala
defmap[U](f:T=>U):Try[U]

Maps the given function to the value from thisSuccess or returns this if this is aFailure.

Maps the given function to the value from thisSuccess or returns this if this is aFailure.

Attributes

Source
Try.scala
deforElse[U >:T](default:=>Try[U]):Try[U]

Returns thisTry if it's aSuccess or the givendefault argument if this is aFailure.

Returns thisTry if it's aSuccess or the givendefault argument if this is aFailure.

Attributes

Source
Try.scala
defrecover[U >:T](pf:PartialFunction[Throwable,U]):Try[U]

Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess.

Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess. This is like map for the exception.

Attributes

Source
Try.scala

Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess.

Applies the given functionf if this is aFailure, otherwise returns this if this is aSuccess. This is likeflatMap for the exception.

Attributes

Source
Try.scala

ReturnsLeft withThrowable if this is aFailure, otherwise returnsRight withSuccess value.

ReturnsLeft withThrowable if this is aFailure, otherwise returnsRight withSuccess value.

Attributes

Source
Try.scala

ReturnsNone if this is aFailure or aSome containing the value if this is aSuccess.

ReturnsNone if this is aFailure or aSome containing the value if this is aSuccess.

Attributes

Source
Try.scala
deftransform[U](s:T=>Try[U],f:Throwable=>Try[U]):Try[U]

Completes thisTry by applying the functionf to this if this is of typeFailure, or conversely, by applyings if this is aSuccess.

Completes thisTry by applying the functionf to this if this is of typeFailure, or conversely, by applyings if this is aSuccess.

Attributes

Source
Try.scala

Concrete methods

Creates a non-strict filter, which eventually converts this to aFailure if the predicate is not satisfied.

Creates a non-strict filter, which eventually converts this to aFailure if the predicate is not satisfied.

Note: unlike filter, withFilter does not create a new Try. Instead, it restricts the domain of subsequentmap,flatMap,foreach, andwithFilter operations.

As Try is a one-element collection, this may be a bit overkill, but it's consistent with withFilter on Option and the other collections.

Value parameters

p

the predicate used to test elements.

Attributes

Returns

an object of classWithFilter, which supportsmap,flatMap,foreach, andwithFilter operations. All these operations apply to those elements of this Try which satisfy the predicatep.

Source
Try.scala

Inherited methods

The name of the nth element of this product, 0-based.

The name of the nth element of this product, 0-based. In the default implementation, an empty string.

Value parameters

n

the index of the element name to return

Attributes

Returns

the name of the specified element

Throws

IndexOutOfBoundsExceptionif then is out of range(n < 0 || n >= productArity).

Inherited from:
Product
Source
Product.scala

An iterator over the names of all the elements of this product.

An iterator over the names of all the elements of this product.

Attributes

Inherited from:
Product
Source
Product.scala

An iterator over all the elements of this product.

An iterator over all the elements of this product.

Attributes

Returns

in the default implementation, anIterator[Any]

Inherited from:
Product
Source
Product.scala

A string used in thetoString methods of derived classes.

A string used in thetoString methods of derived classes. Implementations may override this method to prepend a string prefix to the result oftoString methods.

Attributes

Returns

in the default implementation, the empty string

Inherited from:
Product
Source
Product.scala

Inherited and Abstract methods

Checks whether this instance can possibly equalthat.

Checks whether this instance can possibly equalthat.

A method that should be called from every well-designed equals method that is open to be overridden in a subclass. SeeProgramming in Scala, Chapter 28 for discussion and design.

Value parameters

that

the value being probed for possible equality

Attributes

Returns

true if this instance can possibly equalthat, otherwise false

Inherited from:
Equals
Source
Equals.scala

The size of this product.

The size of this product.

Attributes

Returns

for a productA(x1, ..., xk), returnsk

Inherited from:
Product
Source
Product.scala

The nth element of this product, 0-based.

The nth element of this product, 0-based. In other words, for a productA(x1, ..., xk), returnsx(n+1) where0 <= n < k.

Value parameters

n

the index of the element to return

Attributes

Returns

the elementn elements after the first element

Throws

IndexOutOfBoundsExceptionif then is out of range(n < 0 || n >= productArity).

Inherited from:
Product
Source
Product.scala
In this article
Generated with
Copyright (c) 2002-2025, LAMP/EPFL
Copyright (c) 2002-2025, LAMP/EPFL

[8]ページ先頭

©2009-2025 Movatter.jp