Scala Partital Function

Hi All, I’m learning Scala now. When going through Partial function definition and usage, I understood use of it, but have a question.

In almost all Google link about Scala Partitial function, I can see the function definition has 2 input parameters, but in code block we are using only one (i.e. 1st) or we pass only 1 parameter.

Can someone please help me here to explain this? We can have only one parameter in definition, since we pass only one.

val r = new PartialFunction[Int, Int]

        // Applying isDefinedAt method  
        def isDefinedAt(q: Int) = q != 0

        // Applying apply method 
        def apply(q: Int) = 12 * q 


    // Displays output if the 
    // condition is satisfied 

Where do you see two input parameters?
Function and PartialFunction’s last type-parameter is the return-value.

I thought second is input parameter.

because in general when we define function, then it is like

functionToAdd(a: Int, b:Int) :Double=

Where Double is return type.

Am I learning wrong way?

Hello @ace_friends22 welcome to Scala.

Don’t use Google / chatGPT for learning. They are often wrong about Scala.

Get the book written by language creator, “Programming in Scala 5th edition”. It explains partial functions very well:

The Google code you are showing is almost never used directly.
We do not create partial functions by directly using PartialFunction[X,Y].
Instead we use case expressions / pattern matching.

The PartialFunction[X,Y] is a mechanism that Scala uses “behind the scenes” to convert case expressions to partial functions with the correct type. Sometimes this is used directly to explain how it works (like the book does in the screenshot).

Much better learning resources for Scala:

Anyway, to answer the question, PartialFunction[X,Y] is a function that takes X as input type, and returns Y as output type. That’s why it looks like “two input parameters”. But the second one is actually the type of the output.

Yes probably. You are lacking crucial information.

Type parameters and input parameters are different. This is also explained in the book, Chapter 18, “Type Parameterization”:

So you see, you really have to learn Scala properly from a good source. It’s not like a typical programming language. Some languages don’t even have type parameters.

Hope this helps!

1 Like

Thank you. I’ll follow learning path as you mentioned.


I just want to second that it’s essential to have a book. Google and ChatGPT are supplementary, not primary.

1 Like