Search code examples
f#fsi

F# unbox<int> returns obj


Perhaps a silly question, but why does the return value from unbox appear (in my F# Interactive session) to be typed as obj instead of the concrete type int? As far as I can understand (trying to apply existing knowledge from C#) if it's typed as obj then it's still boxed. Example follows:

> (unbox<int> >> box<int>) 42;;
val it : obj = 42
> 42;;
val it : int = 42

Solution

  • Function composition (f >> g) v means g (f (v)), so you're actually calling box<int> at the end (and the call to unbox<int> is not necessary):

    > box<int> (unbox<int> 42);;
    val it : obj = 42
    
    > box<int> 42;;
    val it : obj = 42
    

    The types are box : 'T -> obj and unbox : obj -> 'T, so the functions convert between boxed (objects) and value types (int). You can call unbox<int> 42, because F# automatically inserts conversion from int to obj when calling a function.