F# generic type constraints and duck typing

后端 未结 3 1054
心在旅途
心在旅途 2020-12-19 00:21

I\'m trying to implement duck typing in F# and I spotted that you can have a member constraint in F# generics as follows:

type ListEntryViewModel<\'T wh         


        
3条回答
  •  醉酒成梦
    2020-12-19 01:00

    Is it possible to implement duck typing via a generic constraint?

    No. Except for a few special cases F# implements only nominal typing where duck typing is not possible. As the other answers have explained, the idiomatic "solution" is to retrofit an interface onto all of the classes that you wish had adhered to that interface but, of course, that is impractical in most cases where you want duck typing.

    Note that this limitation in F# is inherited from .NET. If you want to see a more practical solution akin to duck typing, check out OCaml's structurally typed polymorphic variants and objects.

提交回复
热议问题