Create a closure from shared in Scala

I'm trying to do something that I'm not sure what a system like Scala will allow me to do.

I basically want to create a closure from the general definition and return this closure when the function is executed inside the same type.

For instance:

val f = async[(str:String, i:Int, b:BigInt) => Unit]({ (String, Int, BigInt) =>
  // Code here...
})

// 'f' would have a type of (String, Int, BigInt) => Unit and would wrap the passed anonymous function

Theoretical example definition:

  def async[T](
    shell: Shell,
    success: T,
    failure: (Throwable) => Unit): T = {
        new T {
          val display = shell.getDisplay()
          display.asyncExec(new Runnable() {
            def run(): Unit = {
              try {
                success(_)
              } catch {
                case e:Throwable =>
                  failure(e)
              }
            }
          })
        }
  }

This would allow me to create a simple system for creating asynchronous callbacks for SWTs, leaving SWTs out of my business logic.

+5
source share
2 answers

You can do this more generally with the Shapeless library . Define wrapas follows:

import shapeless._, Functions._

def wrap[F, A <: HList, R](f: F)(implicit
  h: FnHListerAux[F, A => R],
  u: FnUnHListerAux[A => R, F]
): F = { (args: A) => 
  println("Before f")
  val result = f.hlisted(args)
  println("After f")
  result
}.unhlisted

And then you can use it as follows:

scala> val sum: (Int, Int) => Int = _ + _
sum: (Int, Int) => Int = <function2>

scala> val wrappedSum = wrap(sum)
wrappedSum: (Int, Int) => Int = <function2>

scala> wrappedSum(100, 1)
Before f
After f
res0: Int = 101

This works with any arity function.

, Scala, - Shapeless .

+9

- :

scala> def wrap[T1, T2, T3, R](f: (T1, T2, T3) => R) = {
 |   (v1: T1, v2: T2, v3: T3) =>
 |     println("Before f")
 |     val r = f(v1, v2, v3)
 |     println("After f")
 |     r
 | }
wrap: [T1, T2, T3, R](f: (T1, T2, T3) => R)(T1, T2, T3) => R

scala> def foo(x: String, y: Int, z: BigInt) = (x, y, z)
foo: (x: String, y: Int, z: BigInt)(String, Int, BigInt)

scala> val wrapped = wrap(foo _)
wrapped: (String, Int, BigInt) => (String, Int, BigInt) = <function3>

scala> wrapped("foo", 42, 12345)
Before f
After f
res0: (String, Int, BigInt) = (foo,42,12345)

, , , , , : - (

+2

All Articles