Alk
Alk

Reputation: 5557

F# type error in function return value

I'm trying to implement the following code snippet in F#:

    // Method style
void Callback (NSNotification notification)
{
    Console.WriteLine ("Received a notification UIKeyboard", notification);
}

void Setup ()
{
    NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillShowNotification, Callback);
}

I have done the following:

let toggleKeyboard(notification : NSNotification) = 
    Console.WriteLine ("Received a notification UIKeyboard", notification)

NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.WillShowNotification, toggleKeyboard) |> ignore

This seems like a straightforward implementation, however I get a type error:

This expression was expected to have type 'Action<NSNotification>' but here has type ''a -> unit' (FS0001) (Dissertation)

I'm not really sure how to make my method return a Action<NSNotification> type.

Upvotes: 1

Views: 60

Answers (1)

Taylor Wood
Taylor Wood

Reputation: 16194

Sometimes F# will automatically cast functions to Action<T> or Func<T> types, but you can also explicitly wrap your function in an Action<T> like this:

let foo x = printfn "%s" x
let action = System.Action<string>(foo)
action.Invoke("hey") // prints hey

Or in your case:

...AddObserver(UIKeyboard.WillShowNotification, System.Action<NSNotification>(toggleKeyboard)) |> ignore

Upvotes: 3

Related Questions