I'm not sure why F# seems to allow the definition of a class without any constructors. I mean, it would be impossible to instantiate an object of the class. Shouldn't the language spec treat this as illegal behavior?
For example, I can define the class
type myClass =
class
member this.x = 0
end
myClass
seems to have the type
type myClass =
member x: int
But it would not be instantiable.
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass.
Constructors are called by the compiler automatically; they are rarely called explicitly by the programmer. If you write no constructor, the compiler will provide your class with a default constructor.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
The only way you can make an object is to construct it - so you can never initialize a class without a constructor.
In my experience, the object-oriented features of F# can sometimes be less elegant than what C# enables you to express. The above question could be one example; another example is automatically implemented mutable properties.
Most people (including me) seem not to care, because we rarely use those features. The object-oriented features of F# mainly exist in order to enable interoperation with other .NET code, so while they can be useful, they aren't the important parts of the language. My guess is that no one thought of implementing that compiler check because it wouldn't provide much value. As soon as you'd attempt to use myClass
, you'd notice that something was wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With