Skip to content

Upcast branches of match and if expressions when type is specified #792

@charlesroddie

Description

@charlesroddie

F# should upcast return values of if and match expressions where the required type is known. For example the following expressions should compile:

type View() = class end
type Label() = inherit View()
let f b :View =
    if b
    then View()
    else Label() // FS0001 "All branches of an 'if' expression must return values of the same type as the first branch..."
let g b :View =
    match b with
    | true -> View()
    | false -> Label() // FS0001 "All branches of a pattern match expression must..."
let h b :View =
    match b with
    | true -> Label() // FS0001 "This expression was expected to have type View..."
    | false -> View()

Currently up-casting (where the intended type is specified or known) happens automatically in lists (let l:View list = [ Label() ]) and in function inputs. This doesn't happen in if and match constructs. There may be other constructs where this also doesn't happen, which should be added to this suggestion.

Pros and Cons

The advantages of making this adjustment to F# are: less manual upcasting

The disadvantages of making this adjustment to F# are: none

Extra information

Estimated cost (XS, S, M, L, XL, XXL): M

Related suggestions: There are suggestions also to do with upcasting which are more complex: #3, #536 .

Affidavit (please submit!)

Please tick this by placing a cross in the box:

  • [ x ] This is not a question (e.g. like one you might ask on stackoverflow) and I have searched stackoverflow for discussions of this issue
  • [ x ] I have searched both open and closed suggestions on this site and believe this is not a duplicate
  • [ x ] This is not something which has obviously "already been decided" in previous versions of F#. If you're questioning a fundamental design decision that has obviously already been taken (e.g. "Make F# untyped") then please don't submit it.

Please tick all that apply:

  • [ x ] This is not a breaking change to the F# language design
  • [ x ] I or my company would be willing to help implement and/or test this

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions