Is it somehow possible to declare something like
type F = (Int, Boolean)(implicit String) => Unit
in Scala?
Is it somehow possible to declare something like
type F = (Int, Boolean)(implicit String) => Unit
in Scala?
There is a very important distinction in Scala between "function" and "method":
Functions are values, and can't take arguments by-name, can't be polymorphic, can't be variadic, can't be overloaded, and can't have implicit parameters. While methods can have these, they cannot be passed around as values.
Function types are just traits in the standard library, of the following form:
trait FunctionN[T1, ..., TN, R] {
def apply(x1: T1, ..., xN: TN): R
}
Note how the apply
method in these types does not have an implicit parameter list. Therefore, functions won't ever have implicit parameters.
So if you want to pass "functions" that take implicit parameters, you must create your own trait:
trait Function2I1[T1, T2, I1, R] {
def apply(a1: T1, a2: T2)(implicit i1: I1): R
}
type F = Function2I1[Int, Boolean, String, Unit]
Now you can create instances of type F
(albeit not with shiny lambda syntax):
val f = new F {
override def apply(x: Int, y: Boolean)(implicit z: String): Unit = ???
}
implicit val x = "hi"
f(1, true) // implicitly passes x
If you want curried functions without implicit parameters, just write (Int, Boolean) => String => Unit
.
If you want to convert a method to a function, use a lambda:
class A {
def f(a: String)(implicit b: String): String = a + b
}
val a = new A
val m = a.f(_) // takes the implicit in this scope
© 2022 - 2024 — McMap. All rights reserved.