F # Inheritance

I understand that F # entries are unsealed classes. if so, can I inherit the record type? For instance:

type person = {name:string; address:string} type employee inherit person = {employeeId: string} 

I have a search on MSDN docs and language specifications, and I'm out of luck. thanks in advance

+5
source share
2 answers

F # records cannot be inherited, as Matthew mentions, they are compiled for private classes, but it is also an aspect of the F # type system, which simply does not allow this.

In practice, you can go with the usual class declaration. This means that you cannot use the { person with ... } syntax, and you will not get automatic structural equality, but this may make sense if you want to create friendly C # code:

 type Person(name:string) = member x.Name = name type Employee(name:string, id:int) = inherit Person(name) member x.ID = id 

I think that the preferred option would be to use composition rather than inheritance, and make the employee an entry consisting of some personal information and an identifier:

 type PersonalInformation = { Name : string } type Employee = { Person : PersonalInformation ID : int } 

I probably would not have made a person a part of an employee (which I donโ€™t think is right, but this is just an intuition), so I renamed it PersonalInformation here.

I believe another option would be to have IPerson as an interface and have an Employee entry that implements the interface:

 type IPerson = abstract Name : string type Employee = { ID : int Name : string } interface IPerson with member x.Name = x.Name 

Which one best depends on the specific thing you are modeling. But I find that interfaces and composition are usually preferred in F # :-)

+20
source

These are private classes, here are the first few lines of the class generated for person :

 [CompilationMapping(SourceConstructFlags.RecordType)] [Serializable] public sealed class person : IEquatable<person>, IStructuralEquatable, IComparable<person>, IComparable, IStructuralComparable 
+8
source

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


All Articles