Say I have something looking like this:
def curriedHelper[T](foo: String)(f: String => T) = f(foo)
This is just something simplified. Point being that I have some work to be done and later apply another transformation where the resulting type is yet to be determined. Maybe foo here is a db-collection name and f is a function from a DB-cursor to different record types.
Here Scala's currying falls short for me since T needs to be fixed already on partial application. Its simply not useful since Scala fixes T to Nothing:
scala> val partiallyAppliedToNothing = curriedHelper("bar") _
partiallyAppliedToNothing: (String => Nothing) => Nothing = <function1>
So then I have typically done something like
def curriedHelper2(foo: String) = new {
def apply[T](f: String => T) = f(foo)
}
val better = curriedHelper2("bar")
However, this I just noticed uses reflection
val usesReflection = better{ x =>
try {
throw new NullPointerException
} catch {
case e => e.printStackTrace
}
x
}
Stacktrace show reflection being used to invoke apply. I can't understand why this needs to be reflection like structural typing in general. Could just be an inner class, right?
So I guess the only thing remaining is to name this to avoid reflection:
trait WhatDoICallThis[F] {
def apply[T](f: (F => T)): T
}
def curriedHelper3(foo: String) = new WhatDoICallThis[String] {
def apply[T](f: String => T) = f(foo)
}
Are there any standard classes for this?