Reputation: 47904
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>]
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
Upvotes: 2
Views: 545
Reputation: 4433
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.
Upvotes: 1
Reputation: 118865
No, you have to cast:
let getA i : A =
if i = 0 then upcast new B() else upcast new C()
Upvotes: 6