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

PartialFunction

scala.PartialFunction
See thePartialFunction companion object
traitPartialFunction[-A,+B] extendsA=>B

A partial function of typePartialFunction[A, B] is a unary function where the domain does not necessarily include all values of typeA. The functionisDefinedAt allows to test dynamically if a value is in the domain of the function.

Even ifisDefinedAt returns true for ana: A, callingapply(a) may still throw an exception, so the following code is legal:

val f: PartialFunction[Int, Any] = { case x => x / 0 }   // ArithmeticException: / by zero

It is the responsibility of the caller to callisDefinedAt before callingapply, because ifisDefinedAt is false, it is not guaranteedapply will throw an exception to indicate an error condition. If an exception is not thrown, evaluation may result in an arbitrary value.

The usual way to respect this contract is to callapplyOrElse, which is expected to be more efficient than calling bothisDefinedAt andapply.

The main distinction betweenPartialFunction andscala.Function1 is that the user of aPartialFunction may choose to do something different with input that is declared to be outside its domain. For example:

val sample = 1 to 10def isEven(n: Int) = n % 2 == 0val eveningNews: PartialFunction[Int, String] = {  case x if isEven(x) => s"$x is even"}// The method collect is described as "filter + map"// because it uses a PartialFunction to select elements// to which the function is applied.val evenNumbers = sample.collect(eveningNews)val oddlyEnough: PartialFunction[Int, String] = {  case x if !isEven(x) => s"$x is odd"}// The method orElse allows chaining another PartialFunction// to handle input outside the declared domain.val numbers = sample.map(eveningNews orElse oddlyEnough)// same asval numbers = sample.map(n => eveningNews.applyOrElse(n, oddlyEnough))val half: PartialFunction[Int, Int] = {  case x if isEven(x) => x / 2}// Calculating the domain of a composition can be expensive.val oddByHalf = half.andThen(oddlyEnough)// Invokes `half.apply` on even elements!val oddBalls = sample.filter(oddByHalf.isDefinedAt)// Better than filter(oddByHalf.isDefinedAt).map(oddByHalf)val oddBalls = sample.collect(oddByHalf)// Providing "default" values.val oddsAndEnds = sample.map(n => oddByHalf.applyOrElse(n, (i: Int) => s"[$i]"))

Attributes

Note

OptionalFunctions,PartialFunctions and extractor objects can be converted to each other as shown in the following table.  

How to convert ...

to aPartialFunction

to an optionalFunction

to an extractor

from aPartialFunction

Predef.identity

lift

Predef.identity

from optionalFunction

Function1.UnliftOps#unlift orFunction.unlift

Predef.identity

Function1.UnliftOps#unlift

from an extractor

{ case extractor(x) => x }

extractor.unapply _

Predef.identity

 

Companion
object
Source
PartialFunction.scala
Graph
Supertypes
traitA=>B
classObject
traitMatchable
classAny
Known subtypes
traitMapOps[K,V,CC,C]
traitMapOps[K,V,CC,C]
traitMap[K,V]
classAbstractMap[K,V]
classHashMap[K,V]
classIntMap[T]
classListMap[K,V]
classLongMap[T]
classMap1[K,V]
classMap2[K,V]
classMap3[K,V]
classMap4[K,V]
classWithDefault[K,V]
classWithDefault[K,V]
classTreeMap[K,V]
classTreeSeqMap[K,V]
classVectorMap[K,V]
traitSeqMap[K,V]
traitSortedMap[K,V]
traitSortedMapOps[K,V,CC,C]
traitStrictOptimizedMapOps[K,V,CC,C]
traitMapOps[K,V,CC,C]
classTrieMap[K,V]
classAnyRefMap[K,V]
classHashMap[K,V]
classLinkedHashMap[K,V]
classListMap[K,V]
classLongMap[V]
traitMap[K,V]
traitMap[K,V]
classAbstractMap[K,V]
classWithDefault[K,V]
classWithDefault[K,V]
classOpenHashMap[Key,Value]
classTreeMap[K,V]
traitMultiMap[K,V]
traitSeqMap[K,V]
traitSortedMap[K,V]
traitSortedMapOps[K,V,CC,C]
traitMap[K,V]
classAbstractMap[K,V]
traitDefaultMap[K,V]
traitSeqMap[K,V]
traitSortedMap[K,V]
traitMapFactoryDefaults[K,V,CC,WithFilterCC]
classWeakHashMap[K,V]
traitMapView[K,V]
classAbstractMapView[K,V]
classFilter[K,V]
classFilterKeys[K,V]
classId[K,V]
classMapValues[K,V,W]
classTapEach[K,V,U]
traitSortedMapFactoryDefaults[K,V,CC,WithFilterCC,UnsortedCC]
traitSortedMapOps[K,V,CC,C]
traitStrictOptimizedMapOps[K,V,CC,C]
traitSeq[A]
traitSeq[A]
classAbstractSeq[A]
classArraySeq[A]
classofBoolean
classofByte
classofChar
classofDouble
classofFloat
classofInt
classofLong
classofRef[T]
classofShort
classofUnit
classLazyList[A]
classList[A]
class::[A]
objectNil
classNumericRange[T]
classExclusive[T]
classInclusive[T]
classQueue[A]
classRange
classExclusive
classInclusive
classStream[A]
classCons[A]
objectEmpty
classVector[A]
traitIndexedSeq[A]
traitLinearSeq[A]
traitSeq[A]
classAbstractSeq[A]
classArrayBuffer[A]
classArrayDeque[A]
classQueue[A]
classStack[A]
classListBuffer[A]
classArraySeq[T]
classofBoolean
classofByte
classofChar
classofDouble
classofFloat
classofInt
classofLong
classofRef[T]
classofShort
classofUnit
traitBuffer[A]
traitIndexedBuffer[A]
traitIndexedSeq[T]
classAccumulator[A,CC,C]
classAbstractSeq[A]
traitIndexedSeq[A]
traitLinearSeq[A]
Show all
Self type

Members list

Value members

Abstract methods

Checks if a value is contained in the function's domain.

Checks if a value is contained in the function's domain.

Value parameters

x

the value to test

Attributes

Returns

true, iffx is in the domain of this function,false otherwise.

Source
PartialFunction.scala

Concrete methods

overridedefandThen[C](k:B=>C):PartialFunction[A,C]

Composes this partial function with a transformation function that gets applied to results of this partial function.

Composes this partial function with a transformation function that gets applied to results of this partial function.

If the runtime type of the function is aPartialFunction then the otherandThen method is used (note its cautions).

Type parameters

C

the result type of the transformation function.

Value parameters

k

the transformation function

Attributes

Returns

a partial function with the domain of this partial function, possibly narrowed by the specified function, which maps argumentsx tok(this(x)).

Definition Classes
Source
PartialFunction.scala

Composes this partial function with another partial function that gets applied to results of this partial function.

Composes this partial function with another partial function that gets applied to results of this partial function.

Note that callingisDefinedAt on the resulting partial function may apply the first partial function and execute its side effect. For efficiency, it is recommended to callapplyOrElse instead ofisDefinedAt orapply.

Type parameters

C

the result type of the transformation function.

Value parameters

k

the transformation function

Attributes

Returns

a partial function with the domain of this partial function narrowed by other partial function, which maps argumentsx tok(this(x)).

Source
PartialFunction.scala
defapplyOrElse[A1 <:A,B1 >:B](x:A1,default:A1=>B1):B1

Applies this partial function to the given argument when it is contained in the function domain.

Applies this partial function to the given argument when it is contained in the function domain. Applies fallback function where this partial function is not defined.

Note that expressionpf.applyOrElse(x, default) is equivalent to

if(pf isDefinedAt x) pf(x) else default(x)

except thatapplyOrElse method can be implemented more efficiently. For all partial function literals the compiler generates anapplyOrElse implementation which avoids double evaluation of pattern matchers and guards. This makesapplyOrElse the basis for the efficient implementation for many operations and scenarios, such as:

- combining partial functions intoorElse/andThen chains does not lead to excessiveapply/isDefinedAt evaluation -lift andunlift do not evaluate source functions twice on each invocation -runWith allows efficient imperative-style combining of partial functions with conditionally applied actions

For non-literal partial function classes with nontrivialisDefinedAt method it is recommended to overrideapplyOrElse with custom implementation that avoids doubleisDefinedAt evaluation. This may result in better performance and more predictable behavior w.r.t. side effects.

Value parameters

default

the fallback function

x

the function argument

Attributes

Returns

the result of this function or fallback function application.

Source
PartialFunction.scala

Composes another partial functionk with this partial function so that this partial function gets applied to results ofk.

Composes another partial functionk with this partial function so that this partial function gets applied to results ofk.

Note that callingisDefinedAt on the resulting partial function may apply the first partial function and execute its side effect. For efficiency, it is recommended to callapplyOrElse instead ofisDefinedAt orapply.

Type parameters

R

the parameter type of the transformation function.

Value parameters

k

the transformation function

Attributes

Returns

a partial function with the domain of other partial function narrowed by this partial function, which maps argumentsx tothis(k(x)).

Source
PartialFunction.scala

Returns an extractor object with aunapplySeq method, which extracts each element of a sequence data.

Returns an extractor object with aunapplySeq method, which extracts each element of a sequence data.

Attributes

Example

val firstChar: String => Option[Char] = _.headOptionSeq("foo", "bar", "baz") match {  case firstChar.unlift.elementWise(c0, c1, c2) =>    println(s"$c0, $c1, $c2") // Output: f, b, b}
Source
PartialFunction.scala
deflift:A=>Option[B]

Turns this partial function into a plain function returning anOption result.

Turns this partial function into a plain function returning anOption result.

Attributes

Returns

a function that takes an argumentx toSome(this(x)) ifthis is defined forx, and toNone otherwise.

See also

Function.unlift

Source
PartialFunction.scala
deforElse[A1 <:A,B1 >:B](that:PartialFunction[A1,B1]):PartialFunction[A1,B1]

Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

Composes this partial function with a fallback partial function which gets applied where this partial function is not defined.

Type parameters

A1

the argument type of the fallback function

B1

the result type of the fallback function

Value parameters

that

the fallback function

Attributes

Returns

a partial function which has as domain the union of the domains of this partial function andthat. The resulting partial function takesx tothis(x) wherethis is defined, and tothat(x) where it is not.

Source
PartialFunction.scala
defrunWith[U](action:B=>U):A=>Boolean

Composes this partial function with an action function which gets applied to results of this partial function.

Composes this partial function with an action function which gets applied to results of this partial function. The action function is invoked only for its side effects; its result is ignored.

Note that expressionpf.runWith(action)(x) is equivalent to

if(pf isDefinedAt x) { action(pf(x)); true } else false

except thatrunWith is implemented viaapplyOrElse and thus potentially more efficient. UsingrunWith avoids double evaluation of pattern matchers and guards for partial function literals.

Value parameters

action

the action function

Attributes

Returns

a function which maps argumentsx toisDefinedAt(x). The resulting function runsaction(this(x)) wherethis is defined.

See also

applyOrElse.

Source
PartialFunction.scala
defunapply(a:A):Option[B]

Tries to extract aB from anA in a pattern matching expression.

Tries to extract aB from anA in a pattern matching expression.

Attributes

Source
PartialFunction.scala

Inherited methods

defcompose[A](g:A=>A):A=>B

Composes two instances ofFunction1 in a newFunction1, with this function applied last.

Composes two instances ofFunction1 in a newFunction1, with this function applied last.

Type parameters

A

the type to which functiong can be applied

Value parameters

g

a function A => T1

Attributes

Returns

a new functionf such thatf(x) == apply(g(x))

Inherited from:
Function1
Source
Function1.scala
overridedeftoString():String

Returns a string representation of the object.

Returns a string representation of the object.

The default representation is platform dependent.

Attributes

Returns

a string representation of the object.

Definition Classes
Inherited from:
Function1
Source
Function1.scala

Inherited and Abstract methods

defapply(v1:A):B

Apply the body of this function to the argument.

Apply the body of this function to the argument.

Attributes

Returns

the result of function application.

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

[8]ページ先頭

©2009-2025 Movatter.jp