Posts Android and F# are at last friends

Android and F# are at last friends

A long time ago.., ok sometime at around the end of last year (2016), Android’s terrible relationship with F# was about to improve significantly. Xamarin Forms was possible with an F# Core, but many, myself included, resorted to using a C# Droid project.

What was the problem you ask? every time the project is recompiled, or the R file is regenerated, the resource IDs are recalculated. One would assume that an F# project should have F# an F# resource file, but it turns out that some of the names were reserved keywords in F#. Causing the project, not the build. The F# resource file had to be edited manually to put quotes around the reserved keywords to get the project to compile. Everything was fine until that file changed or a recompile was required again. 1000 attempts were not needed

The team at Xamarin kept working away at this bug with many attempts, but a bolder move was required. The final solution was to use one of F#’s superpowers, yes, a type provider. The generated resource file was left as a C# file, no more pesky keywords. A Resources type provider was then created to read off the resources file. This addressed all the problems making Android development in F# a pleasant experience. For those not familiar with a type provider, it is like a compiler plugin to the F# compiler,

I wrote an intro here learn about type providers How do I use it

In your favourite IDE, it should be Visual Studio since it’s now on Mac too, the default templates have been updated to include the resources type provider. To access the resources though, you will need to add one line. The following should be added at the top of your fs file, or before all your activities/fragments

// assuming the droid namespace is MyGreatAndroidProject.Droid
type Resources = MyGreatAndroidProject.Droid.Resource

With that line added, it’s now possible to access your resources. For example, to get the main page would be


If for some reason the resources are not appearing, then restart the IDE as it is most likely that the file was not added to the solution correctly (an error with the IDE). Go forth with Android and F# in harmony - for example, you could convert a Xamarin Forms project to 100% F#. Here is how to set up the core project with MvvmCross and FSharp Oh and here’s the original bug report for those who want a full read up: F# reserved keyword ‘end’ being generated in member for resource.designer.fs

This post is licensed under CC BY 4.0 by the author.