I have a function exec
which accepts 3 parameters and applies a function f
passed as first argument to the other two - p1
and p2
.
def exec[T](f: (T, T) => Boolean, p1: T, p2: T) = f(p1, p2)
Everything works fine if I declare in advance a function which will be passed as an argument.
Somehow compiler can infer types for arguments of eq
or in other words it can figure out that whatever
in this case is Int
// declaring a function with type parameter (polymorphic method)
def eq[whatever](p1: whatever, p2: whatever) = p1 == p2
// using a declared function
println(exec(eq, 10, 10))
It also works fine if I explicitly specify Int
as shown below
// specifying type explicitly in function literal
println(exec((p1: Int, p2: Int) => p1 == p2, 10, 10))
// specifying type parameter
println(exec[Int]((p1, p2) => p1 == p2, 10, 10))
Question 1
Is it possible to get below working?
println(exec((p1, p2) => p1 == p2, 10, 10))
For example, by using implicits, defining exec
differently or using some other way making it possible for compiler to infer types of p1 and p2 so that it does not fail with missing parameter type
.
So no explicit type hints or declared methods are used.
Question 2
How does compiler infer types for eq
and why it works for expressions like p1 == p2
or p1 != p2
but fails for p1 >= p2
(error is value >= is not a member of type parameter whatever
)?