Declare a Function `type` with `implicit` parameters
Asked Answered
G

1

17

Is it somehow possible to declare something like

type F = (Int, Boolean)(implicit String) => Unit

in Scala?

Grits answered 19/2, 2016 at 10:22 Comment(1)
Sorry I deleted my comment, it was "you can do type f = (Int, Boolean) => (String) => Unit anyway". You're right in saying that it doesn't work with implicits, I guess it's because you should not depend on them in your types. A function that takes an Int and a Boolean is a function that takes an Int and a Boolean regardless of the implicits in scope. edit: Ok, ven answered below, a method is not a function, and fuctions don't have implicitsHedgehop
M
24

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
Millda answered 19/2, 2016 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.