0

I have recently come across a Scala class in my project which has parameters like currying. For Example:

class A (a:Int,b:Int)(c:Int){
/** 
Some definition
**/
}
  1. What is the advantage of these kind of parameterization?

  2. When I create an object as val obj = new A(10,20)

I am getting runtime error.

Can anyone explain?

1
  • Super-quick answer: if you know a and b but don't yet know c, it may be beneficial to partially-build an instance of A, that can be given to something that can finish the job Commented Feb 13, 2018 at 5:12

1 Answer 1

2

What is the advantage of these kind of parameterization?

I can think of two possible advantages:

  1. Delayed construction.

You can construct part of the instance in one area of the code base...

val almostA = new A(10, 20)(_)

...and complete it in a different area of the code.

val realA = almostA(30)
  1. Default parameter value.

Your example doesn't do this, but a curried parameter can reference an earlier parameter.

class A (a:Int,b:Int)(c:Int = a){ . . .

When I create an object as val obj = new A(10,20) I am getting runtime error.

You should be getting a compile-time error. You either have to complete the constructor parameters, new A(10,20)(30), or you have to leave a placeholder, new A(10,20)(_). You can leave the 2nd parameter group off only if it has a default value (see #2 above).

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

2 Comments

The first isn't a reason for currying, because you can do exactly the same without currying: val almostA = new A(10, 20, _). It's more relevant for methods where currying can simplify syntax.
@AlexeyRomanov; excellent point. I couln't make that compile but now I realize why. Type ascription is required: almostA = new A(10, 20, _:Int)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.