ToString throws a NullReferenceException for unit () value

Say we got a very simple function

let fn a = a.ToString()

This type is inferred as a -> string However, passing a unit value to a function throws a NullReferenceException.

In the case of simple functions like the ones described above, this can easily work, but I am in a more complex scenario:

let eitherToHttp e = 
    match e with
    | Either.Ok v ->        OK (v.ToString()) 
    | Either.Bad reason ->  reasonToErrorCode reason

Type this Either<'a, RejectReason> -> WebPart(that WebPartand Eitheractually it does not matter here)

In a scenario where the type eis equal Either<unit, RejectReason>, the function is thrown just like in a simple scenario.

How can I handle this? Should types be inferred as generic if this does not actually work for ALL types?

+4
2

- :

let fn a = match box a with
           | null -> ""
           | _ -> a.ToString()

a, ToString.

+3

string ToString :

> string 42;;
val it : string = "42"
> string ();;
val it : string = ""
+6

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


All Articles