Question

In scala, Can you explain what is the difference between them, and why the first one...

In scala,

Can you explain what is the difference between them, and why the first one use "() => Int", and second one use "Int => () => Int"

1.

val constant5 : () => Int = {
()=>5
}

2.
val constant : Int => () => Int = {
(n :Int)=>(()=> n )
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

There's a minute difference between the two statements in Scala.

1. Statement 1 will always return constant i.e 5 which is an integer value. No matter where this function is being called it will always return integer value 5. It does not accepts any parameter so we can call this function from anywhere like below:

val a : Int = constant5()

So, a will have value of 5 returned from statement 1.

Similarly you can return any value by making same constant structure and just changing the digit part of the constant. For ex- if you want a constant that return a number 'X' write:

val a : Int = constantX()

2. Statement 2 is generalized function which accepts an Integer parameter and returns the same integer value that is being given as parameter. You can pass any Integer value to this function call and it will return that same integer value. It is also called an Identity function. You can use this as below:

val a: () => Int = constant (2)

This above statement will return a function, to fetch the value use below statement.

val b: Int = a ()

So, here we called function 'a' returned from above statement and it will give us our value 2 which was given as parameter.

The reason why the first one uses "() => Int" and second one uses "Int => () => Int" is that first one accepts no parameter and returns the constant as specified in its declaration whereas second one accepts or requires an Integer parameter to be passed and it returns the same Integer parameter when the function is being called anywhere in the program.

Add a comment
Know the answer?
Add Answer to:
In scala, Can you explain what is the difference between them, and why the first one...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT