Masahiko Miyasaka
Masahiko Miyasaka

Reputation: 191

Why F# type inference doesn't work for class or interface?

F# type inference works for only F# related types except for class or interface. But I don't know why. I understand candidates will increase, but it's impossible? Are there other reasons?

Upvotes: 0

Views: 76

Answers (1)

monoceres
monoceres

Reputation: 4770

It's simply impossible to determine what the type is of an object in many circumstances. The most basic case being something like:

type A () = member x.bar () = ()
type B () = member x.bar () = ()

let foo x = x.bar () // Is x A or B?

The compiler does its best though, so if it knows what the type is at the time of usage it will happily allow you to skip the annotations:

type A () = member x.bar () = ()
type B () = member x.bar () = ()
let blah (x: A) = x.bar () 

let foo x =
   blah x
   x.bar () // x is known to be A thanks to above line

A more in depth discussion can be found in my old question here: Why is type inference impractical for object oriented languages?

Upvotes: 1

Related Questions