F# function with polymorphic (in the OO sense) return type
Is it possible to have a function return multiple types as long as they share a common base class, without casting each return value?
For example:
[<AbstractClass>开发者_JAVA百科;]
type A() =
abstract Do : unit -> unit
type B() =
inherit A()
override x.Do() = ()
type C() =
inherit A()
override x.Do() = ()
let getA i : A =
if i = 0 then new B() else new C() //Error: This expression was expected to have type A but here has type B
No, you have to cast:
let getA i : A =
if i = 0 then upcast new B() else upcast new C()
I believed you could use generics with constraints to define a return type of 'a when a :> SomeType but I've now got to fire up VS to check.
Edit: nope.. curses... you'll have to cast.
精彩评论