Skip to content

SAM extending Function1 causes anonymous class to be generated #19387

Open
@armanbilge

Description

@armanbilge

Compiler version

3.4.0-RC1-bin-20240104-2746ee8-NIGHTLY

Minimized code

//> using scala 3.4.0-RC1-bin-20240104-2746ee8-NIGHTLY

trait Foo[-A, +B] {
  def apply(a: A): B
}

trait Bar[-A, +B] extends Foo[A, B]

trait Baz[-A, +B] extends Function1[A, B]

class Test {
  def captureFunction1[A, B](f: Function1[A, B]): Unit = ()
  def captureFoo[A, B](f: Foo[A, B]): Unit = ()
  def captureBar[A, B](f: Bar[A, B]): Unit = ()
  def captureBaz[A, B](f: Baz[A, B]): Unit = ()

  def test() = {
    captureFunction1[String, String](_.length.toString)
    captureFoo[String, String](_.length.toString)
    captureBar[String, String](_.length.toString)
    captureBaz[String, String](_.length.toString)
  }
}

Output

/*
 * Decompiled with CFR 0.151.
 */
import java.io.Serializable;
import scala.Function1;
import scala.runtime.BoxesRunTime;

public class Test {
    public <A, B> void captureFunction1(Function1<A, B> f) {
    }

    public <A, B> void captureFoo(Foo<A, B> f) {
    }

    public <A, B> void captureBar(Bar<A, B> f) {
    }

    public <A, B> void captureBaz(Baz<A, B> f) {
    }

    public void test() {
        this.captureFunction1((Function1<String, String> & Serializable)_$1 -> BoxesRunTime.boxToInteger(_$1.length()).toString());
        this.captureFoo(_$2 -> BoxesRunTime.boxToInteger(_$2.length()).toString());
        this.captureBar(_$3 -> BoxesRunTime.boxToInteger(_$3.length()).toString());
        this.captureBaz(new Baz<String, String>(this){
            {
                if ($outer == null) {
                    throw new NullPointerException();
                }
            }

            public final String apply(String _$4) {
                return Test.Test$$_$test$$anonfun$4(_$4);
            }
        });
    }

    public static final /* synthetic */ String Test$$_$test$$anonfun$4(String _$4) {
        return BoxesRunTime.boxToInteger(_$4.length()).toString();
    }
}

Expectation

Implementing a SAM (single abstract method) should avoid generating an anonymous class.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions