Understanding the change to use protected / base member in F # 3.0

F # 3.0 adds more stringent checks for calls to base and protected members. I have something like the following abstract class in C # that has protected static helper methods that will be used by derived classes.

 public abstract class Processor { public abstract void Process(); protected static void Helper(object arg) { } } 

In F #, one of those helper methods is passed as a function of the first class:

 type DerivedProcessor() = inherit Processor() let init f = f () override x.Process() = init Processor.Helper 

It compiles without complaint in version 2.0, but in version 3.0 an error occurs:

A protected element is invoked or "base" is used. This is allowed only with the direct implementation of elements, since they can hide the scope of the object.

OK, this is easy enough to do, just wrap the call in another static member

 static member private HelperWrapper(arg) = Processor.Helper(arg) 

and pass it on. But why?

C # has no problems with the same template.

 public class HappyToCompile : Processor { private void Init(Action<object> f) { f(null); } public override void Process() { Init(Helper); } } 

Questions:

  • Why were more stringent checks added?
  • (and related) What a terrible problem makes such a trivial workaround?
  • Is there a better design that should encourage?
+6
source share
1 answer

Using my mental language skills, I would suggest that F # 2.0 generates unchecked code. See this Eric Lippert blog article for an explanation of a related issue in C # (which has been fixed with C # 4, IIRC).

In short, when you create the F # function, you really create a new class from FSharpFunc<_,_> , and the call to the protected method from this class is invalid because it is not in the inheritance chain.

Of course, instead of barring these calls, the compiler could just do what you are doing (create a private method and use it), but perhaps the benefits were not considered to outweigh the costs of implementing this improvement.

+5
source

Source: https://habr.com/ru/post/923682/


All Articles