Daniel
Daniel

Reputation: 47904

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>]
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

Answers (2)

Massif
Massif

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

Brian
Brian

Reputation: 118865

No, you have to cast:

let getA i : A =
  if i = 0 then upcast new B() else upcast new C()

Upvotes: 6

Related Questions