I don't really know what the proper title for this question should be, but:
I have a discriminated union called MyDiscriminatedUnion
in F#
:
type MyDiscriminatedUnion =
| Foo of Foo
| Bar of Bar
where Foo
and Bar
are record types:
type Foo = {
... }
type Bar = {
... }
I created a value of union type Foo
:
let foo = Foo {
... }
The compiler tells me that foo is of type MyDiscriminatedUnion
.
Then I want to pass foo into a function that expects type Foo, not MyDiscriminatedUnion
. Therefore the compiler complains. How do I tell the compiler that foo
is of type Foo
?
I have tried:
let foo:Foo
when constructing the value of union type.
I have tried to "downcast" foo to Foo by:
foo :?> MyDiscriminatedUnion.Foo
but neither of them work.
Please help.
This is a common mistake when coming from an OO language: there are no subtypes involved in this code. The fact that you named your union cases the same as the type of the field they contain can make this confusing though, so let me give a slightly different example:
Its_a_Foo
andIts_a_Bar
are not subtypes, they're union cases. A value of typeMyDiscriminatedUnion
is either anIts_a_Foo
, in which case it has a field of typeFoo
, or anIts_a_Bar
, in which case it has a field of typeBar
. To know which one it is and get the corresponding field, you need to use pattern matching.