Hello all,
I was wondering if someone could explain why this code fails, since it seems trivial to me:
case class TestClass(field: Double)
object Main {
def getField[T, U](obj: T, fn: T => U): U = fn(obj)
def main(args: Array[String]) = {
val tt = new TestClass(32.1)
getField(tt, _.field)
}
}
The call to "getField" does not like its second parameter, when surely it should be able to determine that "[T] = TestClass". My hunch is that it is for some reason getting a more generic type like "Any", but why? Especially when this is fine, and surely only serves to confirm that "[T]" is what I think it is:
getField(tt, {_.field}: TestClass => Double)
I've tried multiple variations, such as "{ x => x.field }" (doesn't work), explicitly giving "[TestClass, Double]" (works, but very verbose), "Function1[T, U]" instead of "T => U" (didn't help at all, and I didn't think it would).
This also works, and I'm not sure where the fundamental difference is in the type checking. The only problem is that this design doesn't work well for my end-target (this is obviously just a reduced example):
case class TestClass(field: Double)
object Main {
implicit class Getter[T](obj: T) {
def getField[U](fn: T => U): U = fn(obj)
}
def main(args: Array[String]) = {
val tt = new TestClass(32.1)
tt.getField(_.field)
}
}
Any ideas?
Thanks,
Alex "Y_Less" Cole