Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes without constructor in F#

Tags:

.net

f#

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.

like image 206
Shuheng Zheng Avatar asked Oct 08 '15 11:10

Shuheng Zheng


People also ask

Can you have a class without a constructor?

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.

What happens if there is no constructor in a class?

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.

Do all classes need constructors?

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.

Can we initialize a class without making constructor?

The only way you can make an object is to construct it - so you can never initialize a class without a constructor.


1 Answers

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.

like image 117
Mark Seemann Avatar answered Nov 11 '22 12:11

Mark Seemann