Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why implicit class in Scala must reside in another trait/class/object?

Tags:

scala

Based on the scala documentation: http://docs.scala-lang.org/overviews/core/implicit-classes.html, the implicit class has three restrictions, and the very first one, I quote here, is

They must be defined inside another trait/class/object

What is the intuition/reason to explain/justify such a restriction?

like image 864
Chu-Cheng Hsieh Avatar asked Jun 01 '15 21:06

Chu-Cheng Hsieh


1 Answers

An implicit class decomposes into a "normal" class and an implicit method that instantiates the class:

implicit class IntOps(i: Int) { def squared = i * i }

Is rewritten as

class IntOps(i: Int) { def squared = i * i }
implicit def IntOps(i: Int) = new IntOps(i)

But in Scala, you cannot define a method (def IntOps) outside of an object or a class. That is why.

like image 135
0__ Avatar answered Oct 01 '22 01:10

0__