# Implicit Function Types

**URL:** <https://contributors.scala-lang.org/t/implicit-function-types/219>\
**Category:** Dotty\
**Created:** [December 7, 2016, 8:08pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219 "2016-12-07T20:08:56Z")\
**Posts on this page:** 12\
**Page:** 3

<div class="post-metadata">

**Author:** ![AMatveev](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/amatveev/32/847_2.png) [@AMatveev](https://contributors.scala-lang.org/u/AMatveev)\
**Post date:** [May 23, 2018, 1:57pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/42 "2018-05-23T13:57:11Z")

</div>

Thanks a lot.

I think, “Static Scope Injection” is quite easy and enough. “Scope Injection” can be implemented with “Static Scope Injection” and “implicit function type”

I hope that one day “Static Scope Injection” will be implemented in dotty. It will make scala-dsl more powerful and more convenient.

---

<div class="post-metadata">

**Author:** ![LPTK](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/lptk/32/1620_2.png) [@LPTK](https://contributors.scala-lang.org/u/LPTK)\
**Post date:** [May 24, 2018, 2:59pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/43 "2018-05-24T14:59:20Z")

</div>

> [@pweisenburger](#):
>
> I think that scope injection is a more direct solution to this issue. I guess that you cannot encode the exact same feature with implicit function types only. Could be that the encoding is good enough though, so that we don’t want to have scope injection as a separate concept; not fully sure about the best trade-off.

Yes, you end up with the identifiers in the global scope, also accessible from outside of the restricted context, so the encoding is not exactly equivalent. But IMHO it doesn’t warrant adding such a complex feature as scope injection, because you can have a nice error message when the construct is used outside of its scope and the implicit is not found, reading something like “this construct can only be used inside the scope of […] construct”, which I’d say is good enough.

---

<div class="post-metadata">

**Author:** ![AMatveev](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/amatveev/32/847_2.png) [@AMatveev](https://contributors.scala-lang.org/u/AMatveev)\
**Post date:** [May 24, 2018, 4:37pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/44 "2018-05-24T16:37:56Z")

</div>

I’m interested, will it work with “Currying”:

```auto
def someFuntion(arg:SomeType)(implicit arg:SomeImplicitType)

```

In any case, the scope injection allow to:

- Use third libraries
- Minimize possible conflicts in global scope

---

<div class="post-metadata">

**Author:** ![DWvanGeest](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/dwvangeest/32/2298_2.png) [@DWvanGeest](https://contributors.scala-lang.org/u/DWvanGeest)\
**Post date:** [May 24, 2018, 4:57pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/45 "2018-05-24T16:57:21Z")

</div>

@mdedetrich Thanks for the reply which I just managed to see now (yikes). Your example is compelling and something I see frequently. Just to make sure I’m understanding, I think you’re saying that your example would be replaced as follows:

```auto
def doSomething(param: String)(implicit client: HttpExt, ec: ExecutionContext, materializer: Materializer) = ...

```

becomes:

```auto
def doSomething(param: String): Contextualized[...]

```

Where `Contextualized` essentially defines those implicit dependencies. This does cut down on the boilerplate, however I will say that I also see a pattern like this:

```auto
def doSomething(param: String)(implicit ctx: Context) = {
  implicit val ec = ctx.ec
  implicit val materializer = ctx.materializer
  // ...
}

```

I suppose this last variation also has boilerplate that gets stripped away in the declaration of the `implicit val`s, so it does save something. I suppose what I continue to question is the cost of muddying the waters between inputs and outputs, as discussed above.

I _am_ getting the idea that implicit function types are useful for more than just cutting down on boilerplate, and that’s good. But originally I was responding to the stated motivation.

---

<div class="post-metadata">

**Author:** ![AMatveev](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/amatveev/32/847_2.png) [@AMatveev](https://contributors.scala-lang.org/u/AMatveev)\
**Post date:** [May 25, 2018, 9:00am UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/46 "2018-05-25T09:00:35Z")

</div>

For comparison, there is extension in kotlin:  
see: [https://kotlinlang.org/docs/reference/extensions.html](https://kotlinlang.org/docs/reference/extensions.html)  
With this functionality we can make sql dsl:

```auto
fun search(name: String, minAge: Int?) = list {
    where {
        upper(c.name) like upper("%$name%")
        if (minAge != null) {
            and {
                c.age gte minAge
            }
        }
    }
}

```

In this example “where” is declared as:

```auto
fun where(op: WhereExpr.() -> Unit) =
            add(WhereExpr(this), op)

```

see:[https://github.com/edvin/kdbc/blob/master/src/main/kotlin/kdbc/expression.kt](https://github.com/edvin/kdbc/blob/master/src/main/kotlin/kdbc/expression.kt)

This is equivalent of scope injection.  
It’s very convenient.

---

<div class="post-metadata">

**Author:** ![pweisenburger](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/pweisenburger/32/401_2.png) [@pweisenburger](https://contributors.scala-lang.org/u/pweisenburger)\
**Post date:** [May 25, 2018, 11:33am UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/47 "2018-05-25T11:33:10Z")

</div>

> [@LPTK](#):
>
> Yes, you end up with the identifiers in the global scope, also accessible from outside of the restricted context, so the encoding is not exactly equivalent. But IMHO it doesn’t warrant adding such a complex feature as scope injection, because you can have a nice error message when the construct is used outside of its scope and the implicit is not found, reading something like “this construct can only be used inside the scope of […] construct”, which I’d say is good enough.

> [@AMatveev](#):
>
> This is equivalent of scope injection.
> 
> It’s very convenient.

Right, I can totally see both points. Scope injection is very convenient, but it also adds complexity to the language which may be unnecessary since you can also encode it. Having all values in the global scope (using the encoding) can be become more of problem when you start to have name clashes between identifiers.

> [@AMatveev](#):
>
> I’m interested, will it work with “Currying”:
> 
> ```scala
> def someFuntion(arg:SomeType)(implicit arg:SomeImplicitType)
> 
> ```

Yes, currying should work, e.g., with the current plugin, you can write:

```scala
def someFuntion(arg:SomeType): Int `implicit =>` (SomeTypeT `implicit =>` SomeTypeU)

```

---

<div class="post-metadata">

**Author:** ![AMatveev](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/amatveev/32/847_2.png) [@AMatveev](https://contributors.scala-lang.org/u/AMatveev)\
**Post date:** [May 25, 2018, 1:19pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/48 "2018-05-25T13:19:35Z")

</div>

> [@pweisenburger](#):
>
> Yes, currying should work

Currying does not have overloading, for example:

```auto
class OverloadingTest extends FunSuite {
  def doNothing(a: Int)(implicit b:String): Unit = {}
  def doNothing(a: Int)(implicit b:BigDecimal): Unit = {}
  test("string") {
    implicit val b: String = ""
    doNothing(1)
  }
}

```

compiled with:

```auto
Error:(13, 5) ambiguous reference to overloaded definition,

```

So, in global scope, there will be conflicts very quickly.

I have understood that scala has many complexity. And views(implicit val) make code quite surprising.  
But, "import anorm.\_ " in the head of the file can be real headache. And there is no ability to easily overcome it now.  
☹

---

<div class="post-metadata">

**Author:** ![milessabin](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/milessabin/32/115_2.png) [@milessabin](https://contributors.scala-lang.org/u/milessabin)\
**Post date:** [May 31, 2018, 1:50pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/49 "2018-05-31T13:50:31Z")

</div>

I’m a little surprised to learn that there’s no syntax for implicit function _values_.

I was expecting that if given something like,

```scala
type Foo = implicit (Int, String) => implicit Boolean => Int

```

I would be able to write,

```scala
val foo: Foo =
  implicit (i: Int, s: String) => implicit (b: Boolean) =>
    s.length + i + (if(b) 1 else 0)

```

As it stands it seems that you’d either need to write methods to be eta expanded,

```scala
def foo1(implicit b: Boolean) = s.length + i + (if(b) 1 else 0)
def foo2(implicit i: Int, s: String): implicit Boolean => Int = foo1
val foo: Foo = foo2

```

or work with `implicitly`,

```scala
val blah: Foo =
  implicitly[String].length + implicitly[Int] + (if(implicitly[Boolean]) 1 else 0)

```

Neither of which are particularly pleasant.

I think we need to be able to name implicit function arguments if we’re going to be able to combine this feature cleanly with _dependent_ function types. For instance, I think we ought to be able to write things along the lines of,

```scala
trait Bar { type T }
type Foo = implicit (b: Bar) => b.T => ...

```

More generally, I think we should be aiming to make implicit/dependent/polymorphic completely orthogonal, at least sufficiently to allow for a one-one correspondence between method types and function types.

---

<div class="post-metadata">

**Author:** ![odersky](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/odersky/32/42_2.png) [@odersky](https://contributors.scala-lang.org/u/odersky)\
**Post date:** [June 1, 2018, 8:08am UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/50 "2018-06-01T08:08:45Z")

</div>

Good point. Implicit closures are supported (same as in Scala 2.12) but the syntax does not allow to give a parameter type. I.e. all you can do is:

```
implicit x => ...

```

We should generalize that to arbitrary closures.

---

<div class="post-metadata">

**Author:** ![yangbo](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/yangbo/32/81_2.png) [@yangbo](https://contributors.scala-lang.org/u/yangbo)\
**Post date:** [June 5, 2018, 10:53am UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/51 "2018-06-05T10:53:16Z")

</div>

Alternatively, we can create non-implicit functions and implicitly apply it.

The alternative approach is implemented in a library called **feature.scala** :

> **[ThoughtWorksInc/feature.scala](https://github.com/ThoughtWorksInc/feature.scala)**
>
> Access Scala language features on the type-level. Contribute to ThoughtWorksInc/feature.scala development by creating an account on GitHub.

Examples can be found in [its Scaladoc](https://javadoc.io/page/com.thoughtworks.feature/implicitapply_2.12/latest/com/thoughtworks/feature/ImplicitApply.html).

---

<div class="post-metadata">

**Author:** ![ibaklan](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/ibaklan/32/933_2.png) [@ibaklan](https://contributors.scala-lang.org/u/ibaklan)\
**Post date:** [September 26, 2018, 7:25pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/52 "2018-09-26T19:25:55Z")

</div>

I think non-static scope injection is very nice feature, it is heavily exploited in Kotlin for convenient and easy  
way to [define builders/dsl](https://kotlinlang.org/docs/reference/type-safe-builders.html) and prove to be really powerful thing.  
It is build on top of Katlin’s [extension methods](https://kotlinlang.org/docs/reference/extensions.html)/ [extension functions / extension lambadas](https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver)  
And in fact it is really close to

> [@pweisenburger](#):
>
> type `implicit import =>`[-T, +R] = T =\> R

But use rather “extension” instead of “implicit” word  
So Kotlin’s

```auto
ThisArg.() -> ResultType

```

Should become something like

```Scala
ThisArg `extension import =>` ResultType

```

using **DSL Paradise** notation, or alternatively I personally would prefer something like

```Scala
// without regular arguments - similar to Kotlin's `ThisArg.() -> ResultType`
(@this @import ThisArg) => ResultType
// or with them - similar to Kotlin's `ThisArg.(RegularArg1, RegularArg2) -> ResultType`
(@this @import ThisArg, RegularArg1, RegularArg2) => ResultType

```

Also I think it could be very interesting to know that Kotlin also allows to resolve “scope injection clashes” via  
marking different blocks/lambdas by labels: it is available as [Qualified this expression](https://kotlinlang.org/docs/reference/this-expressions.html#qualified)

Brief demonstration of that Kotlin’s features may look like this:

Kotlin’s [extension methods](https://kotlinlang.org/docs/reference/extensions.html)/[functions/lambadas](https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver):

```Kotlin
    fun testExtensions() {
        data class PointXY(val x: Int, val y: Int)

        // extension method/function
        fun PointXY.mullXY(): Int {
            // first argument of extension method passed through `this`
            assert(this is PointXY)
            assert(this.x == x)
            assert(this.y == y)
            return x * y;
        }

        // extension filed / local variable / method argument - member of extension function type initialized with extension lambada
        val addXY: PointXY.() -> Int = {
            // first argument of extension lambada passed through `this`
            assert(this is PointXY)
            assert(this.x == x)
            assert(this.y == y)
            x + y;
        }

        // usage
        val p0: PointXY = PointXY(10,6)
        assert(60 == p0.mullXY())
        assert(16 == p0.addXY())
    }

```

Kotlin’s resolution of hidden names ([Qualified this expression](https://kotlinlang.org/docs/reference/this-expressions.html#qualified)):

```Kotlin
    fun testExtensionsScopeResolution() {
        data class PointXY(val x: Int, val y: Int)
        data class PointYZ(val y: Int, val z: Int)

        val pXY = PointXY(1,2)
        val pYZ = PointYZ(3,4)

        // Kotlin( `with(obj) {...}` ) == Kotlin( `obj.apply {...}` ) == Scala( `{import obj._; ... }` )
        with(pXY) labelOuterLambda@ {
            pYZ.apply labelInnerLambda@ {
                // `x` and `z` resolves without clashes
                assert(x == pXY.x)
                assert(z == pYZ.z)
                // `this` resolves to `pYZ` hover all outer `this`-es are also available via qualified notation
                assert(this@labelOuterLambda == pXY)
                assert(this@labelInnerLambda == pYZ && this == pYZ)
                // ambiguity of `y` resolution can be resolved by labels, by default it resolved in nearest scope
                assert(y == pYZ.y && y == this.y)
                assert(this@labelInnerLambda.y == pYZ.y)
                assert(this@labelOuterLambda.y == pXY.y)
            }
        }
    }

```

So I think it would be nice if Scala has something similar or (something better). In my opinion without scope injection in Scala, Kotlin will look much better then Scala in this area.

---

<div class="post-metadata">

**Author:** ![mdedetrich](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/mdedetrich/32/566_2.png) [@mdedetrich](https://contributors.scala-lang.org/u/mdedetrich)\
**Post date:** [September 26, 2018, 7:49pm UTC](https://contributors.scala-lang.org/t/implicit-function-types/219/53 "2018-09-26T19:49:29Z")

</div>

> [@DWvanGeest](#):
>
> Where `Contextualized` essentially defines those implicit dependencies. This does cut down on the boilerplate, however I will say that I also see a pattern like this:

Yes indeed this is correct

> [@DWvanGeest](#):
>
> I suppose this last variation also has boilerplate that gets stripped away in the declaration of the `implicit val` s, so it does save something. I suppose what I continue to question is the cost of muddying the waters between inputs and outputs, as discussed above.

Yeah the point is that sometimes you can’t put all of the config variables inside one global config (or doing so is detrimental for other design reasons).

[Previous page](https://contributors.scala-lang.org/t/implicit-function-types/219.md?page=2)
