开发者

F# function with polymorphic (in the OO sense) return type

开发者 https://www.devze.com 2022-12-12 16:07 出处:网络
Is it possible to have a function return multiple types as long as they share a common base class, without casting each return value?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号