Why does calling Python’s ‘magic method’ not do type conversion like it would for the corresponding operator?

a – b isn’t just a.__sub__(b). It also tries b.__rsub__(a) if a can’t handle the operation, and in the 1 – 2. case, it’s the float’s __rsub__ that handles the operation. >>> (2.).__rsub__(1) -1.0 You ran a.__rsub__(2.), but that’s the wrong __rsub__. You need the right-side operand’s __rsub__, not the left-side operand. There is no … Read more

Why implicitConversions is required for implicit defs but not classes?

Implicit classes effectively only add new methods (or traits), and they are only ever used when these added methods are called (or the implicit class is used explicitly, but this rarely happens in practice). Implicit conversions to existing types, on the other hand, can be invoked with less visibility to the programmer.

Varying behavior for possible loss of precision

That’s because b += 1.0; is equivalent to b = (int) ((b) + (1.0));. The narrowing primitive conversion (JLS 5.1.3) is hidden in the compound assignment operation. JLS 15.26.2 Compound Assignment Operators (JLS Third Edition): A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T … Read more

Why is this function call ambiguous?

It has little to do with rank of the type defined in 4.13. 4.13 defined internal rankings used to describe integral promotions and usual arithmetic conversions. They by itself do not directly affect overload resolution. Rankings relevant to overload resolution are defined in “13.3.3.1.1 Standard conversion sequences” and then used in “13.3.3.2 Ranking implicit conversion … Read more

What is the performance impact of Scala implicit type conversions?

I tried to setup a microbenchmark using the excellent Scala-Benchmark-Template. It is very difficult to write a meaningful (non optimized away by the JIT) benchmark which tests just the implicit conversions, so I had to add a bit of overhead. Here is the code: class FunkyBench extends SimpleScalaBenchmark { val N = 10000 def timeDirect( … Read more

When does lvalue-to-rvalue conversion happen, how does it work, and can it fail?

I think the lvalue-to-rvalue conversion is more than just use an lvalue where an rvalue is required. It can create a copy of a class, and always yields a value, not an object. I’m using n3485 for “C++11” and n1256 for “C99”. Objects and values The most concise description is in C99/3.14: object region of … Read more

tech