简体   繁体   中英

Classes without constructor in 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.

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.

When you create a class with no constructors (in other words, a class that can't be instantiated) you are basically creating an static class*.

In C# you can use the static keyword to allow the compiler to check if you have instance members or not. In F# you don't have such check in compile time.

* Sort of. The proper definition of a static class is one that can't be instantiated or inherited and only has static methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM