Optional parameters in an abstract type type signature

Grade:

type NotAbstract () = 
    member this.WithOptionalParameters (x, ?y) = 
        let y = defaultArg y 10
        x + y

has the following type signature:

type NotAbstract =
  class
    new : unit -> NotAbstract
    member WithOptionalParameters : x:int * ?y:int -> int
  end

However, this does not work:

[<AbstractClass>]
type AbstractExample () = 
    abstract WithOptionalParameters: int * ?int -> int /// Ouch...

type NotAbstract () = 
    inherit AbstractExample ()
    override this.WithOptionalParameters (x, ?y) = 
        let y = defaultArg y 10
        x + y

How to write the correct type signature in an abstract function definition with additional parameters? I did not find any clues here .

PS: I know that a (similar) result can be achieved using polymorphism

+4
source share
3 answers

Declaring an argument as a parameter type does not make the argument optional.

NotAbstract().WithOptionalParameters(2)
// This expression was expected to have type
//     int * Option<int>    
// but here has type
//     int    

spec §8.13.6 has:

In the signature, the optional arguments are as follows: static member OneNormalTwoOptional : arg1:int * ?arg2:int * ?arg3:int -> int

,

[<AbstractClass>]
type AbstractExample () = 
    abstract WithOptionalParameters: int * ?y:int -> int      

type NotAbstract () = 
    inherit AbstractExample ()
    override this.WithOptionalParameters (x, ?y) = 
        let y = defaultArg y 10
        x + y

NotAbstract().WithOptionalParameters(42)  // val it : int = 52
+6

Option, Option<int> ?int:

[<AbstractClass>]
type AbstractExample () = 
    abstract WithOptionalParameters: int * Option<int> -> int      

type NotAbstract () = 
    inherit AbstractExample ()
    override this.WithOptionalParameters (x, ?y) = 
        let y = defaultArg y 10
        x + y
+4

This should work:

[<AbstractClass>]
type AbstractExample () = 
    abstract WithOptionalParameters: int * Nullable<int> -> unit

F # does not have syntactic sugar for types with a null value , so although you can declare a value with a null value with syntax ?y, you cannot do this for a type. You will need to use it instead Nullable<T>.

+2
source

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


All Articles