简体   繁体   中英

Scala - control structure

I am entirely new to Scala world and trying to understand few Scala concepts. From here I got below piece of Scala Code .

def twice(op: Double => Double, x: Double) = op(op(x))

and by calling twice(_ + 1, 5) returning the result Double = 7.0 . But I couldn't able to understand what _ + 1 and op: Double => Double really means. Can someone able to explain me the above piece of code?

op: Double => Double

op is a function that takes a value of type Double and returns a new value of type Double .

_ + 1

_ is the placeholder for an argument to this anonymous function (ie this function is described but has no name. Once it is received in the twice method it has the name op .) So this function takes an argument, adds 1 to it, and returns the new value.

If you call twice(_ + 1, 5) you can think about it like this: op(op(x)) --> op(op(5)) --> op(5 + 1) --> op(6) --> 6 + 1 --> 7 (or 7.0 because it is of type Double )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM