Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currying: How to make first input as optional?

Tags:

scala

I am learning Scala and concept of currying. This is what I am doing

scala> def div(a:Int)(b:Int) = a/b
div: (a: Int)(b: Int)Int

scala> div(10)(2)
res9: Int = 5

scala> val d = div(10)_
d: Int => Int = <function1>

scala> d(5)
res10: Int = 2

scala> val e = div _ (2)
<console>:1: error: ';' expected but '(' found.
       val e = div _ (2)
                     ^

scala> 

Question
- How can I make a as optional and not b?

like image 293
daydreamer Avatar asked Feb 02 '26 17:02

daydreamer


1 Answers

You can fix b and get a function Int => Int, but you need to keep the parentheses, and unfortunately annotate the type:

scala> div(_: Int)(2)
res7: Int => Int = <function1>

scala> res7(10)
res8: Int = 5

scala> res7(2)
res9: Int = 1

a isn't "optional", it's just a parameter in the resulting function.

like image 81
Michael Zajac Avatar answered Feb 05 '26 09:02

Michael Zajac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!