6

The are two different way to implement it.

One is more short

implicit def toR1(s:String) = new { def getLength = s.length)}

Second is more long

class R2(s:String){def getLength2 = s.length)}
implicit def toR2(s:String) = new R2(s)

Which one is better?

0__
  • 66,707
  • 21
  • 171
  • 266
yura
  • 14,489
  • 21
  • 77
  • 126
  • 4
    `implicit class R3(s:String) { def getLength = s.length }` :) I really hope that it will be included in Scala 2.10: http://docs.scala-lang.org/sips/pending/implicit-classes.html – tenshi Feb 22 '12 at 20:17
  • 2
    a possible duplicate: [How to implement intermediate types for implicit methods?](http://stackoverflow.com/questions/5220359/how-to-implement-intermediate-types-for-implicit-methods/5220725). TL;DR the second is better performance-wise as the first way uses reflection under the hood – Paolo Falabella Feb 22 '12 at 20:31
  • implicit classes _are_ included in Scala 2.10, so perhaps the currently only answer to this question is obsolete. – matanster Oct 26 '14 at 22:39

1 Answers1

11

The first version uses a structural type. It makes it possible to write short and readable code, but a disadvantage of structural types is that reflection is used at runtime when you call the method in the structural type. Calling a method via reflection is slower than calling a method directly.

More details are in this blog post (written by me): Avoid structural types when pimping libraries

Jesper
  • 202,709
  • 46
  • 318
  • 350