GNOME Bugzilla – Bug 599349
Ternary operator does not work when assigning a delegate to a local variable
Last modified: 2018-05-22 13:24:20 UTC
This is with Vala 0.7.7: delegate void Delegate(); void call_delegate(Delegate d) { d(); } void heads() { debug("heads"); } void tails() { debug("tails"); } void main() { Rand prng = new Rand(); Delegate d = prng.boolean() ? heads : tails; call_delegate(d); } Produces this error output: test.vala:19.35-19.39: error: Assignment: Cannot convert from `heads' to `heads' Delegate d = prng.boolean() ? heads : tails; ^^^^^ test.vala:19.43-19.47: error: Assignment: Cannot convert from `tails' to `tails' Delegate d = prng.boolean() ? heads : tails; ^^^^^ test.vala:19.18-19.31: error: Incompatible expressions Delegate d = prng.boolean() ? heads : tails; ^^^^^^^^^^^^^^ test.vala:19.14-19.47: error: expression type not allowed as initializer Delegate d = prng.boolean() ? heads : tails; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ test.vala:21.19-21.19: error: The name `d' does not exist in the context of `main' call_delegate(d); ^ Compilation failed: 5 error(s), 0 warning(s) make: *** [test] Error 1 However, if I replace the ternary operator with a traditional if-else statement: Delegate d = null; if (prng.boolean()) d = heads; else d = tails; Compiles and runs fine.
The ternary operator works fine if heads&tails are casted to the Delegate type. delegate void Delegate(); void call_delegate(Delegate d) { d(); } void heads() { debug("heads"); } void tails() { debug("tails"); } void main() { Rand prng = new Rand(); unowned Delegate d = prng.boolean() ? (Delegate)heads : (Delegate)tails; call_delegate(d); }
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/vala/issues/51.