Quantcast
Channel: User Tarmil - Stack Overflow
Viewing all articles
Browse latest Browse all 38

Answer by Tarmil for F# Discriminated Union - "downcasting" to subtype

$
0
0

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:

type MyDiscriminatedUnion =  | Its_a_Foo of Foo  | Its_a_Bar of Bar

Its_a_Foo and Its_a_Bar are not subtypes, they're union cases. A value of type MyDiscriminatedUnion is either an Its_a_Foo, in which case it has a field of type Foo, or an Its_a_Bar, in which case it has a field of type Bar. To know which one it is and get the corresponding field, you need to use pattern matching.

// The function that takes a record of type Foo as argumentlet f (x: Foo) = ...// Our value of type MyDiscriminatedUnionlet myDU = Its_a_Foo { ... }// Extracting the Foo and passing it to fmatch myDU with| Its_a_Foo foo -> f foo| Its_a_Bar bar -> // What should we do if it's an Its_a_Bar instead?// If you're _really_ certain that myDU is Its_a_Foo { ... }, not Its_a_Bar { ... }, you can do this.// You will get a compile-time warning "FS0025: Incomplete pattern matches on this expression".// If it's Its_a_Bar, you will get a runtime error.let (Its_a_Foo foo) = myDUf foo

Viewing all articles
Browse latest Browse all 38

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>