Is there a better way of modeling data in F# to avoid needing it?
Default: When no access modifier is specified for a class, method, or data member – It is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.
Protecting a constructor prevents the users from creating the instance of the class, outside the package. During overriding, when a variable or method is protected, it can be overridden to other subclass using either a public or protected modifier only. Outer class and interface cannot be protected.
Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private . Class and struct members, including nested classes and structs, have private access by default.
The protected
modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected
member, the following code could be surprising:
type Base() = protected member x.Test(a) = a > 10 type Inherited() = inherit Base() member x.Filter(list) = list |> List.filter (fun a -> x.Test(a))
This code wouldn't work, because you're calling Test
from a lambda function (which is a different object than the current instance of Test
), so the code wouldn't work. I think this is tha main reason for not supporting the protected
modifier in F#.
In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn't need protected
as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected
in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?
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