简体   繁体   中英

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM