Scala abusive implicit conversion

In scala 2.10 REPFL:

> class E(val i: Int) { def += (other: E) = i - other.i } implicit def toE(i: Int) = new E(i) var j = 1 j += 3 

Results in:

 res1: Int = -2 > j j: Int = 1 

Note that there is no hindrance to regular += if class E itself is marked as implicit, compared to using the previous conversion method.

Wow, I was able to completely harm the program if it is an implicit transformation in the field! Is there a way to ask scala not to convert to implicits if a value already exists?

+4
source share
2 answers

I cannot answer if this behavior can be changed, but I found the following description in the specification (p. 85):

Assignment operators are specially processed so that they can be extended to assignments if no other interpretation is valid . Let's look at an assignment operator, such as + = in the operation in fi l + = r, where l, r are expressions. This operation can be reinterpreted as the operation corresponding to the task l = l + r

From this, I understand that since you provided an alternative interpretation, the extension does not occur. Myabe will be helpful in finding a problem.

+3
source

The other answer does not indicate the entire passage from the specification, which is explicit:

Re-interpretation occurs if the following two conditions are met. 1. The left side l does not have a member with the name + =, and also cannot be converted by an implicit conversion (§6.26) into a value with a member called + =.

(Another condition is typechecks.)

When you make a class implicit, you defined two implicit conversions (one of which is your toE ) that are ambiguous and silently ignored. (This is a feature of the genus.)

So, you answered your question: one way to disable the implicit is to make it ambiguous.

Another way is to obscure the name, since the implicit must be accessible by a simple name.

In the event of chaos breaking: now you know why you should import scala.language.implicitConversions .

I think you also know what F --- means in REPFL [sic].

+3
source

Source: https://habr.com/ru/post/1496177/


All Articles