Implicit typing in languages like C# permits compile-time type checks without necessarily referring "directly" to a target class:
var toy = SantasWorkshop.Build();
toy.amuse();
In this scenario, we don't need to know what type of toy
it is. And yet, we'll still know at compile-time whether our toy
fails to amuse()
.
However, this is limited to the local scope. If we want to put that toy
into a Stocking
and retain the compile-time checks, we need to know something about it at compile time -- other than it's ability to amuse()
. E.g., this is illegal:
class Stocking {
List<var> toys;
public void add(var toy) {
toys.add(toy);
}
}
If we're willing to sacrifice on the compile-time check, languages like C# allow us to use dynamic typing:
class QuestionableLookingStocking {
List<dynamic> toysIHope;
public void add(dynamic toyIHope) {
toysIHope.add(toyIHope);
}
}
But, this will allow us to add objects to a QuestionableLookingStocking
that may not actually amuse()
. And we won't know about it until someone adds Coal
at runtime.
class Coal {
public ChristmasMood ruinChristmas() {
return new SadChristmas();
}
}
Would it be logically possible and feasible for implicit typing to be extended to members? I.e., is there any reason the compiler couldn't complain if someone tries to Stocking.add()
an object that doesn't support the operations required by all references to Stocking.toys[n]
?
Are there patterns that could simulate implicit member types?