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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With