1

I see the following code in several places depicting the use of partial functions in Scala.

val divide: PartialFunction[Int, Int] = { case d: Int if d != 0 => 42 / d } 

Here, divide is a variable whose type of is PartialFunction[Int,Int] which is a trait. I am confused about the RHS part. Since the type of the variable "divide" is: PartialFunction[Int,Int] , it needs to be instantiated by using a "new" keyword. I am not sure about the kind of syntax this is. Plus how isdefined() function automatically defined above ? ( isDefined() seems available; but it is there hidden).

Can someone please help.

1
  • 2
    Objects do not have to be instanciated using new, the compiler can create objects directly for literals (0,"Hello") or indeed when it creates a function (which is just an instance of a Function class). In this case it creates an instance of PartialFunction using that syntax. Commented Oct 26, 2020 at 12:41

1 Answer 1

3

The right-hand-side is a function literal in cases.

It's a literal, just like an Int, Char, String don't have a new keyword before the literal.

A function in cases has the syntax

{ case ... => ... (optionally more cases) } 

The expected type must be fully known. If a PartialFunction is expected, it's taken as a PartialFunction. Otherwise, it's taken as a Function1

For the PartialFunction variation, it's isDefinedAt is defined by the patterns of the cases.

Sign up to request clarification or add additional context in comments.

5 Comments

I don't think it has to be a Function1 - afaik it can also expand to a function with multiple parameters.
Thanks for the response! I try to do the following... val x = { case _ => "Nothing" } ad I am getting the error... "Missing parameter type for the expanded function.."
Yes, I forgot, you can only use function literals if the expected type if fully known. val x: Any => String = { case _ => "Nothing" } will work
I have one more question.. When I write, val x = Int=>Int = { case x => 2*x } OR val x: Int=>Int = 2*_ . Both work. But when I do: val y: PartialFunction[Int,Int] = { case x => 2 * x } OR val y: PartialFunction[Int,Int] = 2*_ only the first case works. The second case errors out. Could you please help. though the input type is implicit via the declaration of PartialFunction[Int,Int].
2 * _ is only ever parsed as a Function literal, never as a PartialFunction literal. Only literals in cases are parsed as PartialFunction literals (if one is expected and the argument type is fully known).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.