Allow interfaces to be implemented by expressions
Submitted by Ivan J. Simongauz on 9/3/2016 12:00:00 AM
1 votes on UserVoice prior to migration
Implement interface delegating by next syntax:
type MyType() =
let delegator : IAddingService
interface IAddingService by delegator with
member this.Add x y = // <- this is override
x + y
Special behavior when event in interface - sender substitution
Original UserVoice Submission Archived Uservoice Comments
Related: https://github.com/dotnet/csharplang/issues/477
I think this is an interesting idea, that hasn't gotten much attention. Related (directly inspired by?) kotlin: http://kotlinlang.org/docs/reference/delegation.html
Much in the kotlin example also works out with F#, e.g. delegating to a constructor argument:
type DelegatedAdd(adder:IAddingService) =
interface IAddingService by adder
I think this is an interesting idea, that hasn't gotten much attention. Related (directly inspired by?) kotlin: http://kotlinlang.org/docs/reference/delegation.html
Not inspired by, but it's nice to see. Have been thinking of this from before Kotlin was even a twinkle in JetBrain's eye :)
Hrm, what about something slightly more general purpose. I'd like to be able to do this with object expressions.
And records. Both in terms of value and structure.
Other implementations:
- Dotty has released a version of this featured called
exportin version 0.14: https://dotty.epfl.ch/blog/2019/04/15/14th-dotty-milestone-release.html
I suggest that the expression after by doesn't require to be of the interface type. Instead, the compiler should forward all possible methods and error on missing implementations (the suggestions already shows how to provide them).
This would extend this suggestion to include #195, see https://github.com/fsharp/fslang-suggestions/issues/195#issuecomment-499268087
This might complicate the implementation a bit, but I think it would be well worth it.
I just read an article about using flexible types for dependency injection and I believe that that syntax would greatly help in making a type that merges multiple implementations into a single environment object.
What if we use an equals sign instead of by? There is an earlier example of how it could look here that feels quite natural:
https://github.com/dotnet/csharplang/issues/288#issuecomment-288202651