The example List2Int
should be refused by the compiler, I think, because the compiler should not apply any implicit conversion within the body of method List2Int
.
Yeah, and as I said, you got a point there that may be debated by the contributors of the language.
But, my point is that there is a simple counter-argument, why I have to be explicit if I am using an implicit conversion inside another implicit conversion?
If you are willing to say that implicit conversions inside implicit conversions are dangerous how far are you to say that implicit conversions in general are dangerous?
So, my point is that I believe (note this is completely my personal opinion and subjective) that anyone defending implicit conversion would defend that use case.
Right, you are using the implicit conversion implicit def Any2Unit(x: Any): Unit = ()
. Or, alternatively, it might be that the compiler appends ()
at the end of any method that is defined to have a return type of Unit
.
Yeah, AFAIK, there is no implicit conversion from Any to Unit, it is just that the compiler will add that ()
at the end of the body.
The “use case”, if you want to call it that, would be, for example, that you could implement the method .foreach
of class List[T]
as def foreach(f: T => Unit): Unit
Not sure if this is just curiosity of if you have a real problem with this.
The reason why foreach is not defined as foreach(f: T => Unit)
but instead as foreach[U](f: T => U)
is so you can do something like this:
var globalAcc: Int = 0
/** Adds an amount to the global accumulator and returns its current value. */
def addToAcc(amount: Int): Int = {
globalAcc += amount
globalAcc
}
val data: List[Int] = List(1, 2, 3)
data.foreach(addToAcc)
Now, one may say that it could be defined as foreach(f: T => Any)
and due functions being co-variant on their output, then it should just work. But, I believe that can cause some frustrating errors due things like eta-expansion.
So, again, may I ask; is this just about curiosity or do you have a real problem that you are trying to solve? If so, I would like to help you with that meta-problem.