Question

I have a function

def myInnerFunc(a: Int): Int = a

now I want to pass it to a higher order function and I want it to be passed to the higher order function preinitialized with argument so need to first call my inner function with the proper parameter and only then I can pass it to the higher order function which would make up something like:

def myHigherOrderFunction(func: Int => Int): Int = {
  func()
}

So I need to complete following code

myInnerFunc(1) // hmm fix this will actually call my innner function I just want to preinitialize it with one.
func() // didn't work for me how do i run my preinitialized with argument func Int => Int 
  1. How do I preinitialize myInnerFunc with argument 1 without running it?
  2. How do I run func() from within the higher order function?

I'm not sure how to do that and couldn't really find relevant docs, can anyone please provide an example? (all examples I saw were with multiple arguments I have a single one)

Was it helpful?

Solution 2

Let's take your questions in reverse order:

How do I run func() from within the higher order function?

If the argument has already been provided, it isn't needed again, so the myHigherOrderFunction should look something like this:

def myHigherOrderFunction(func: Unit => Int): Int = { func() }

How do I preinitialize myInnerFunc with argument 1 without running it?

So you need something of type Unit => Int.

val thunk: Unit => Int = { _ => myInnerFunc(argument) }

OTHER TIPS

If you just want to somehow delay the evaluation of f by wrapping it inside another function you can use anonymous functions:

val outer = { () => f(1) }

The reason single parameter currying is not that frequent is because this, given there are no side effects, yields a constant, which is not that exciting or useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top