Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

currying - What's the rationale behind curried functions in Scala?

I am just new to Scala and it seems a little bit confusing to me why Scala provides "curried functions" such as:

//curried function
def add(lhs: Int)(rhs: Int) = lhs + rhs
//so we can do partially binding like
val add1 = add(1)_

Its confusing because Scala already provides 'partial application' to normal functions, e.g.,

//normal function
def add(lhs: Int, rhs: Int) = lhs + rhs
//also supports partially application
val add1 = add(1, _: Int) 

So my question is: is there any other point of using a curried function rather than a normal function in Scala besides partial application?

EDT1: Thanks for the replies. I think I have learned new stuff from all the answers below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Putting the theoretical motivations aside (see: Contrast with partial function application in Wikipedia on currying), there is a practical implication. The syntax is much simpler and more readable when the last argument is a block of code.

Compare the following methods:

def test1(name: String, callback: => Unit) {}
def test2(name: String)(callback: => Unit) {}

The second method invocation looks much nicer, compare:

test("abc", {
    //some code
})

test2("abc") {
    //some code
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...