Question

I want to create a function g that takes a function f as a parameter, where f has a type parameter. I can't get a signature for g that compiles. One attempt is like this:

scala> def mock1[A](): A = null.asInstanceOf[A] // STUB
mock1: [A]()A

scala> def mock2[A](): A = null.asInstanceOf[A] // STUB
mock2: [A]()A

scala> def g0(f: [A]() => A): Int = f[Int]()
<console>:1: error: identifier expected but '[' found.
       def g0(f: [A]() => A): Int = f[Int]()
                 ^

I can get it to work if I wrap the function that takes a type parameter in a trait, like so:

scala> trait FWrapper { def f[A](): A }
defined trait FWrapper

scala> class mock1wrapper extends FWrapper { def f[A]() = mock1[A]() }
defined class mock1wrapper

scala> class mock2wrapper extends FWrapper { def f[A]() = mock2[A]() }
defined class mock2wrapper

scala> def g(wrapper: FWrapper): Int = wrapper.f[Int]()
g: (wrapper: FWrapper)Int

scala> g(new mock1wrapper)
res8: Int = 0

Is there a way I can accomplish this without introducing the wrapper class?

Was it helpful?

Solution

Scala does (currently) not have support for polymorphic function values. You have two options:

  1. Stick with your wrapper trait (probably easiest to understand)
  2. Use polymorphic function values from Shapeless (fancy, but maybe a bit complicated)

OTHER TIPS

How about this:

  def mock[A](): A = null.asInstanceOf[A]

  def g[A](f:() => A): A = f()

  g(mock[Int])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top