Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a protected access modifier in F#?

Tags:

f#

Is there a better way of modeling data in F# to avoid needing it?

like image 894
Daniel Avatar asked Mar 05 '10 22:03

Daniel


People also ask

What happens when no access modifier is specified with the class?

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.

When should we use protected in Java?

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.

Can a class be protected in C#?

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.


1 Answers

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?

like image 169
Tomas Petricek Avatar answered Sep 22 '22 20:09

Tomas Petricek