www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Error: castSwitch

reply none <none mail.com> writes:
import std.algorithm.iteration : map;
import std.algorithm : castSwitch;
import std.format : format;
	
class A { int value; this(int value) { this.value = value; }}
interface I { }
class B : I { }
	
Object[] arr = [new A(5), new B(), null];
auto results = arr.map!(castSwitch!(
	(A a) => "class A with a value of %d".format(a.value),
	(I i) => "derived from I",
	(B b) => "class B",
	() => "null reference",
))();

The codes get nonsense error like:
/home/bthach/dlang/dmd-2.071.0/linux/bin64/../../src/phobos/std/algorith
/comparison.d(277): Error: no property 'format' for type 'string'

But when I changed the order:
[...]
(B b) => "class B",
(I i) => "derived from I",

Suprisingly, it works.
Jun 06 2016
parent Marc =?UTF-8?B?U2Now7x0eg==?= <schuetzm gmx.net> writes:
On Tuesday, 7 June 2016 at 03:55:03 UTC, none wrote:
 import std.algorithm.iteration : map;
 import std.algorithm : castSwitch;
 import std.format : format;
 	
 class A { int value; this(int value) { this.value = value; }}
 interface I { }
 class B : I { }
 	
 Object[] arr = [new A(5), new B(), null];
 auto results = arr.map!(castSwitch!(
 	(A a) => "class A with a value of %d".format(a.value),
 	(I i) => "derived from I",
 	(B b) => "class B",
 	() => "null reference",
 ))();

 The codes get nonsense error like:
 /home/bthach/dlang/dmd-2.071.0/linux/bin64/../../src/phobos/std/algorith
/comparison.d(277): Error: no property 'format' for type 'string'
Note the location of the error: it is in Phobos, not in your code. It's a bug, it should actually print a valid error message. Filed here: https://issues.dlang.org/show_bug.cgi?id=16135 It has nothing to do with the fact that you're using `format`, that's just coincidence.
 But when I changed the order:
 [...]
 (B b) => "class B",
 (I i) => "derived from I",

 Suprisingly, it works.
`castSwitch` tries the types you pass it in the order you specify. If you pass `I` first, the `B` case will never be matched because it is "shadowed" by the former (every `B` is also an `I`). `castSwitch` detects this situation and wants to print a message to warn you. However, someone forgot to import `std.format` (which is used for formatting the error message), resulting in the error you observed.
Jun 07 2016