rockson
rockson

Reputation: 63

Scala 2: generic function that returns another generic function

How can you return a generic function from another generic function? This doesn't work

def gen1[A](a: A) = [B](b: B) => ???

But i don't want to define the second generic in the first function like this

def gen1[A, B](a: A) = (b: B) => ???

Is it possible?

Error here:

illegal start of simple expression
[error]   def gen1[A](a: A) = [B](b: B) => ???
[error]                       ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed

What I'm trying to do is the equivalent of dotty's:

def gen1 = [A] => (a: A) => [B] => (b: B) => (a, b)

But can't find documentation for it in scala 2

Upvotes: 0

Views: 59

Answers (1)

Jasper-M
Jasper-M

Reputation: 15086

Polymorphic functions don't exist in Scala 2. What you can do to get a similar effect is define a custom class with a polymorphic apply method.

class Gen1PartiallyApplied[A](a: A){
  def apply[B](b: B) = ???
}
def gen1[A](a: A) = new Gen1PartiallyApplied(a)
gen1[Int](42)[String]("foo")

Upvotes: 2

Related Questions