Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement intermediate types for implicit methods?

Assume I want to offer method foo on existing type A outside of my control. As far as I know, the canonical way to do this in Scala is implementing an implicit conversion from A to some type that implements foo. Now I basically see two options.

  1. Define a separate, maybe even hidden class for the purpose:

    protected class Fooable(a : A) {
      def foo(...) = { ... }
    }
    implicit def a2fooable(a : A) = new Fooable(a)
    
  2. Define an anonymous class inline:

    implicit def a2fooable(a : A) = new { def foo(...) = { ... } }
    

Variant 2) is certainly less boilerplate, especially when lots of type parameters happen. On the other hand, I think it should create more overhead since (conceptually) one class per conversion is created, as opposed to one class globally in 1).

Is there a general guideline? Is there no difference, because compiler/VM get rid of the overhead of 2)?

like image 1000
Raphael Avatar asked Aug 06 '26 23:08

Raphael


1 Answers

Using a separate class is better for performance, as the alternative uses reflection.

Consider that

new { def foo(...) = { ... } }

is really

new AnyRef { def foo(...) = { ... } }

Now, AnyRef doesn't have a method foo. In Scala, this type is actually AnyRef { def foo(...): ... }, which, if you remove AnyRef, you should recognize as a structural type.

At compile time, this time can be passed back and forth, and everywhere it will be known that the method foo is callable. However, there's no structural type in the JVM, and to add an interface would require a proxy object, which would cause some problems such as breaking referential equality (ie, an object would not be equal with a structural type version of itself).

The way found around that was to use cached reflection calls for structural types.

So, if you want to use the Pimp My Library pattern for any performance-sensitive application, declare a class.

like image 101
Daniel C. Sobral Avatar answered Aug 08 '26 16:08

Daniel C. Sobral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!