Operator Overloading: "Convert" Operator

140 views
Skip to first unread message

Scott Fortmann-Roe

unread,
Feb 13, 2012, 9:41:15 PM2/13/12
to General Dart Discussion
Hi,

Let's say I have a class called Material.

I would like to be able assign a number to an instance of that class.
I have seen this in other languages as an overloading of the "Convert"
operator. Is this possible in Dart?

For example:

class Material{
...
}

Material myMaterial = new Material();

myMaterial = 7; // Dart gives warning: "int is not assignable
to Material". How can I make code to handle this?


Thank you!

A Matías Quezada

unread,
Feb 14, 2012, 3:38:10 AM2/14/12
to Scott Fortmann-Roe, General Dart Discussion
How will you difference when you want to assing 7 to a Material and when you want to assign 7 on the variable than before has a Material instance?

I mean, how will this different behaviours coexists?

var myMaterial = new Material();
myMaterial = 7;
print(myMaterial is Material); // true;
print(myMaterial is num); // false

var myMaterial = new Material();
// do something with myMaterial
// now I want to delete myMaterial
myMaterial = 7;
print(myMaterial is Material); // false;
print(myMaterial is num); // true



2012/2/14 Scott Fortmann-Roe <sco...@gmail.com>

Brook Monroe

unread,
Feb 14, 2012, 6:59:36 AM2/14/12
to General Dart Discussion
Maybe I'm just too old-school about this, but what you're suggesting
seems to me to be the kind of thing that leads to application
defects. Proper application design denies the idea that an explicitly-
typed value should be allowed to abandon that type while it's in
scope.

"Material myMaterial = new Material()" is a contract. "myMaterial =
7" breaks that contract.

Sam McCall

unread,
Feb 14, 2012, 8:48:46 AM2/14/12
to Scott Fortmann-Roe, General Dart Discussion
In Dart, variables don't hold (non-trivial) objects directly, but
rather references. And the = operator binds references to variables
instead of copying values. So it doesn't make sense for dart to
consult the current value of the variable to look for a conversion
operator.
Also, because variable types have no effect on runtime behaviour, Dart
can't consult the type of the variable to look for a conversion.
So there's no way to implement the syntax you want without being
wildly inconsistent with other parts of the language.

I can't tell exactly what you're trying to do, but you can probably
express it using one of these:

// Explicitly convert using a constructor
Material myMaterial;
myMaterial = new Material.fromInt(7);

// Mutate an object using a method


Material myMaterial = new Material();

myMaterial.setValue(7);

// Mutate using a setter


Material myMaterial = new Material();

myMaterial.value = 7;

// Allow your variable to hold either an int or a Material
var myMaterial = new Material();
myMaterial = 7;

Reply all
Reply to author
Forward
0 new messages