# ImplicitFunctionClass

**URL:** <https://contributors.scala-lang.org/t/implicitfunctionclass/2871>\
**Category:** Scala Improvement Process\
**Created:** [February 25, 2019, 1:33pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871 "2019-02-25T13:33:08Z")\
**Posts on this page:** 20\
**Page:** 1

<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:** [February 25, 2019, 1:33pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/1 "2019-02-25T13:33:08Z")

</div>

Dotty supports [implicit function types](https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html)  
Would it be possible implement similar expansion for scala classes and traits:  
for example:

```auto
@FunctionalInterface
abstract class ExtendedFunction extends Function0[Unit]{
  def apply():Unit
}
object Main extends App {
  def doSomeThing(f:ExtendedFunction):Unit = {}
  doSomeThing{
        println("ok")
  }
  println("Hello, World!")
}

```

The main idea of that proposal is that inside a function body of `apply` we have a context of the `ExtendedFunction` class. So we can use methods,variables and implicits of that class.

It will be very useful in dsl api.  
See also:

> [@PRE SIP: ThisFunction | scope injection (similar to kotlin receiver function)](https://contributors.scala-lang.org/t/pre-sip-thisfunction-scope-injection-similar-to-kotlin-receiver-function/2234):
>
> name of feature this functions, dsl function, context functions, receiver function or import function don’t know which name is better. In whole document i’m using this function consequently. specification I propose to introduce additional trait into scala trait ThisFunction[-T, +R] extends Function1[T, R] //trait ReceiverFunction[-T, +R] extends Function1[T, R] //trait ContextFunction[-T, +R] extends Function1[T, R] //trait ImportFunction[-T, +R] extends Function1[T, R] //trait DslFunction[…

> [@DelayedInit or OnCreate, any solution?](https://contributors.scala-lang.org/t/delayedinit-or-oncreate-any-solution/1748):
>
> DelayedInit is [deprecated](https://github.com/scala/scala/pull/3563) in favor a long-pending OnCreate: However, the ticket was recently closed (along with all DelayedInit tickets), which begs the question: what now?

~~There is [FunctionalInterface](https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html) in the java  
The documentation says :  
\_Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references ~~

---

<div class="post-metadata">

**Author:** ![kevinwright](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/kevinwright/32/588_2.png) [@kevinwright](https://contributors.scala-lang.org/u/kevinwright)\
**Post date:** [February 25, 2019, 2:08pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/2 "2019-02-25T14:08:55Z")

</div>

The syntax you’re describing already exists

See [https://www.scala-lang.org/news/2.12.0/#lambda-syntax-for-sam-types](https://www.scala-lang.org/news/2.12.0/#lambda-syntax-for-sam-types)

---

<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:** [February 25, 2019, 2:15pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/3 "2019-02-25T14:15:58Z")

</div>

Unfortunately for classes it does not work

> **[Scastie - An interactive playground for Scala](https://scastie.scala-lang.org/kiGtSQWNSBSUWlo70UfASA)**
>
> Scastie can run any Scala program with any library in your browser. You don’t need to download or install anything.

```auto
[E007] Type Mismatch Error: /tmp/scastie4527384693640219440/src/main/scala/main.scala:8:15 
8 | println("ok")
  | ^^^^^^^^^^^^^
  | found: Unit
  | required: ExtendedFunction
  |        

```

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/jasper-m/32/1192_2.png) [@Jasper-M](https://contributors.scala-lang.org/u/Jasper-M)\
**Post date:** [February 25, 2019, 4:06pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/4 "2019-02-25T16:06:28Z")

</div>

It works, but you have to write an actual lambda `() => println("ok")`.  
A semi-reasonable expectation could be that in

```auto
abstract class ExtendedFunction{
  def execute: Unit // notice: no parameter list
}
def doSomeThing(f: ExtendedFunction):Unit = {}

```

`f` would be treated like a by-name parameter, because `execute` sort of has type `=> Unit`.

Until you can convince someone of actually speccing and implementing that, and having that custom `ExtendedFunction` class is important to you, you could consider this alternative:

```auto
abstract class ExtendedFunction{
  def execute: Unit
}
def doSomeThing(f: => Unit): Unit = {
  val f0 = new ExtendedFunction {
    def execute = f
  }
}

```

---

<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:** [February 25, 2019, 5:31pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/5 "2019-02-25T17:31:08Z")

</div>

> [@Jasper-M](#):
>
> It works, but you have to write an actual lambda `() => println("ok")` .

Thanks, I have mistaken.

Really I do not need “actual lambda”, I need [ImplicitFunction0](https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html)

So that it would work:

```auto
 abstract class ExtendedFunction extends ImplicitFunction0[Unit]{
  def apply():Unit
}
object M{
  def doSomeThing(f: => ExtendedFunction):Unit = {}
  def main(args:Array[String]):Unit = {
      doSomeThing{
        println("ok")
    }
  }
}

```

---

<div class="post-metadata">

**Author:** ![tarsa](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/tarsa/32/784_2.png) [@tarsa](https://contributors.scala-lang.org/u/tarsa)\
**Post date:** [February 25, 2019, 5:39pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/6 "2019-02-25T17:39:32Z")

</div>

Syntax for SAM lambdas is the same, no matter if you’re implementing interface or extending trait or class.

Implicit functions are not about inferring empty parameter lists. They are about inferring implicit function parameters.

---

<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:** [February 25, 2019, 5:43pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/7 "2019-02-25T17:43:58Z")

</div>

> [@tarsa](#):
>
> Implicit functions are not about inferring empty parameter lists.

Ok, I do not know how to make best proposal. Let’s do it together.  
The main idea is creating ExtendedFunction without boilerplate.

I think if we have ImplicitFunction and lambda it will not be hard. And it will open new abilities in dsl libraries.

---

<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:** [February 25, 2019, 6:19pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/8 "2019-02-25T18:19:00Z")

</div>

> [@Jasper-M](#):
>
> def doSomeThing(f: =\> Unit): Unit = { val f0 = new ExtendedFunction { def execute = f } }

It has no sense.

```auto
doSomeThing{ new ExtendedFunction{
        override def execute():Unit = {
            
        }
      }    

```

The main idea of that proposal is that inside a function body of `execute` we have a context of the `ExtendedFunction` class. So we can use methods,variables and implicits of that class.

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/jasper-m/32/1192_2.png) [@Jasper-M](https://contributors.scala-lang.org/u/Jasper-M)\
**Post date:** [February 25, 2019, 6:34pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/9 "2019-02-25T18:34:48Z")

</div>

Ok, that wasn’t very apparent from your initial post. It’s also very different from how SAM types currently work.

---

<div class="post-metadata">

**Author:** ![tarsa](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/tarsa/32/784_2.png) [@tarsa](https://contributors.scala-lang.org/u/tarsa)\
**Post date:** [February 25, 2019, 7:00pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/10 "2019-02-25T19:00:10Z")

</div>

This works in Scala 2.12:

```scala
import scala.language.implicitConversions

object Scala {
  abstract class UncleSam {
    implicit def intToSet(int: Int): Set[Int] = Set(int)

    def definedMethod(x: Set[Int]): String = s"x = $x"

    def abstractMethod(self: UncleSam): Unit
  }

  def doSomeThing(lambda: UncleSam): Unit = {
    lambda.abstractMethod(lambda)
  }

  def main(args: Array[String]): Unit = {
    doSomeThing { self => // you need explicit parameter
      import self._ // and explicit import from it
      println(definedMethod(80))
    }
  }
}

```

There was already a proposal to define `ThisFunction` which would remove the need for

```scala
self =>
import self._

```

and you’ve posted a link to it in first post.

I would like something like the `ThisFunction` proposal for tests. Often I use something like:

```scala
"my class" must "do something important" in test { fixture =>
  import fixture._
  // rest of the test
}

```

Eliding whole `fixture =>` + `import fixture._` would be too disruptive for my taste, but something like:

```scala
"my class" must "do something important" in test { import fixture._ => // shortcut for previous syntax
  // rest of the test with fixture contents visible in scope
}

```

or

```scala
"my class" must "do something important" in test { this fixture =>
  // rest of the test with fixture contents visible in scope
}

```

would be more pleasing.

---

<div class="post-metadata">

**Author:** ![adriaanm](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/adriaanm/32/586_2.png) [@adriaanm](https://contributors.scala-lang.org/u/adriaanm)\
**Post date:** [February 25, 2019, 7:02pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/11 "2019-02-25T19:02:33Z")

</div>

We recently discussed eta expansion and expected types. Most recently at  
[https://github.com/scala/scala/pull/7660](https://github.com/scala/scala/pull/7660)

The main reason we don’t do it for 0-ary SAM types is to avoid confusion when the interface is a SAM by accident (InputStream is a fun example.) We could do the expansion when the type is annotated with FunctionalInterface

---

<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:** [February 25, 2019, 7:27pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/12 "2019-02-25T19:27:51Z")

</div>

> [@tarsa](#):
>
> “my class” must “do something important” in test { this fixture =\> // rest of the test with fixture contents visible in scope }

If I understand correctly [eta expansion](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/11)  
It will be possible somthing like:

```auto
"my class" must "do something important" in test {
  val fixture = this 
  // rest of the test with fixture contents visible in scope 
}

```

But I think it is more rare case. It is similar to [self type](https://docs.scala-lang.org/tour/self-types.html).

---

<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:** [February 26, 2019, 3:24pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/13 "2019-02-26T15:24:10Z")

</div>

If I understand correctly, It have not been done yet.  
Is there any real planning to do it?

```auto
@FunctionalInterface
trait ExtendedFunction extends Function0[Unit]{
  def apply():Unit
}
object Main extends App {
  def doSomeThing(f:ExtendedFunction):Unit = {}
  doSomeThing{
        println("ok")
  }
  println("Hello, World!")
}

Compiling 1 Scala source to C:\buf\scala\sbtTest\hello\target\scala-2.13.0-pre-116ca94-SNAPSHOT\classes ...
[error] C:\buf\scala\sbtTest\hello\src\main\scala\Main.scala:8:16: type mismatch;
[error] found : Unit
[error] required: ExtendedFunction
[error] println("ok")
[error] ^
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed 26.02.2019 18:17:45

```

---

<div class="post-metadata">

**Author:** ![adriaanm](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/adriaanm/32/586_2.png) [@adriaanm](https://contributors.scala-lang.org/u/adriaanm)\
**Post date:** [February 26, 2019, 4:54pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/14 "2019-02-26T16:54:42Z")

</div>

Correct: it hasn’t been implemented, but I think it would make sense to do it.

---

<div class="post-metadata">

**Author:** ![tarsa](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/tarsa/32/784_2.png) [@tarsa](https://contributors.scala-lang.org/u/tarsa)\
**Post date:** [February 27, 2019, 12:12am UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/15 "2019-02-27T00:12:31Z")

</div>

@adriaanm:  
IIUC that still wouldn’t have any effect on `this` or visibility of `ExtendedFuction` members. `this` used in function passed to `doSomething` would still point to `Main` object. Members of `ExtendedFunction` wouldn’t be visible inside function passed to `doSomeThing`. Is that correct?

---

<div class="post-metadata">

**Author:** ![adriaanm](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/adriaanm/32/586_2.png) [@adriaanm](https://contributors.scala-lang.org/u/adriaanm)\
**Post date:** [February 27, 2019, 1:30am UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/16 "2019-02-27T01:30:01Z")

</div>

Yes, I was only referring to the bit about eta expansion of 0-arity Sam types

---

<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:** [February 27, 2019, 6:35am UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/17 "2019-02-27T06:35:44Z")

</div>

I do not think there will be a reasonable sense to do ExtendedFunction if members of ExtendedFunction are not visible inside function passed to doSomeThing. I really need better DalayedInit and Builders.  
Are there any difficulties to do that visability?  
Is it difficult?

> [@AMatveev](#):
>
> doSomeThing{ new ExtendedFunction{ override def execute():Unit = { } }

---

<div class="post-metadata">

**Author:** ![adriaanm](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/adriaanm/32/586_2.png) [@adriaanm](https://contributors.scala-lang.org/u/adriaanm)\
**Post date:** [February 27, 2019, 4:00pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/18 "2019-02-27T16:00:48Z")

</div>

It’s just not what a lambda is. Its `this` is the class it’s contained in. Not sure about having a separate kind of function that changes the meaning of `this` (for one, I don’t think you could compile it to an invokedynamic lambda because these lambdas are not full classes on Java 8).

I can see the motivation for wanting to inject members into scope in a lambda, but not sure about the impact on language complexity.

---

<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:** [February 27, 2019, 5:43pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/19 "2019-02-27T17:43:16Z")

</div>

> [@adriaanm](#):
>
> It’s just not what a lambda is. Its `this` is the class it’s contained in.

Sorry I just do not understand compiler internals well, Why shoud this proposal be a lambda?  
Is it possible to make sugaring or something else to treat it as:

```auto
new ExtendedFunction{ override def execute():Unit = { 
   println("ok")
}

```

If it is hard at least I will not miss this feature 🙂

---

<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:** [February 27, 2019, 8:18pm UTC](https://contributors.scala-lang.org/t/implicitfunctionclass/2871/20 "2019-02-27T20:18:52Z")

</div>

> [@adriaanm](#):
>
> but not sure about the impact on language complexity.

Let us just look (kotlin example)

```auto
class HTML() extend Tag {
    def head(init: Head):Head = initTag(init)
    def body(init: Body):Body = initTag(init)
}

class Head()extend Tag {
    def title(init: Title):Title = initTag(init)
}

class Title() extend Tag 

class BodyTag(name: String) extend Tag {
    def b(init: B):Unit = initTag(init)
    def p(init: P):Unit = initTag(init)
    def h1(init: H1):Unit = initTag(init)
    def ul(init: UL):Unit = initTag(init)
    def a(href: String, init: A):Unit = initTag(init)
}

class Body extend BodyTag("body") 
class UL extend BodyTag("ul") {
    fun li(init: LI):Unit = initTag(init)
}

class B extend BodyTag("b")
class LI extend BodyTag("li")
class P extend BodyTag("p")
class H1 extend BodyTag("h1")

class A extend BodyTag("a") {
    var href: String
}

object Html{
  fun html(init: HTML): HTML = init.initTag
}

```

It is just impossible on “implicit function types”  
Ok, we can make something similar:

```auto
class Table {
  val rows = new ArrayBuffer[Row]
  def add(r: Row): Unit = rows += r
  override def toString = rows.mkString("Table(", ", ", ")")
}

class Row {
  val cells = new ArrayBuffer[Cell]
  def add(c: Cell): Unit = cells += c
  override def toString = cells.mkString("Row(", ", ", ")")
}

case class Cell(elem: String)

object HtmlTable{
    def htmlTable(init: implicit Table => Unit) = {
      implicit val t = new Table
      init
      t
    }

    def row(init: implicit Row => Unit)(implicit t: Table) = {
      implicit val r = new Row
      init
      t.add(r)
    }

    def cell(str: String)(implicit r: Row) =
      r.add(new Cell(str))
}

```

I just do not know how it can be called a simple way.  
There is context independent grammar so we have very high coupling, Methods is detached from its classes. There are very high risks of name clashes.  
Ok we can always say it is not important. It is the question of priorities of cause. But I dream about such ability. It will make my life easier in jpa, html and so on 😉
