Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
What is a "sealed" type in F# and why doesn't the type test pattern operator (:?) work on it out of the `box`?
The F# language guide (see Signatures article) has a very sparse definition of what a "sealed" type is:
Attribute Description [<Sealed>]
For a type that has no abstract members, or that should not be extended. [<Interface>]
For a type that is an interface.
I searched the entire PDF version of the language guide using the term seal
, and this was the most informative (out of all 8 results).
Context: :?
fails on "simple types" with error FS0016
For example, I was playing with type abbreviations when both matches failed
type Lofa = | A | B
type Miez = Lofa
let (a: Miez) = A
match a with | :? Miez -> a
match a with | :? Lofa -> a
with
error FS0016: The type 'Miez' does not have any
proper subtypes and cannot be used as the source
of a type test or runtime coercion.
error FS0016: The type 'Lofa' does not have any
proper subtypes and cannot be used as the source
of a type test or runtime coercion.
The SO thread F# Why can't I use the :? operator in F# interactive? provides an answer (i.e., to use box
, hence the mnemonic pun in the title),
match (box a) with | :? Miez -> a
match (box a) with | :? Lofa -> a
but it doesn't explain why it works or what "sealed" types are, and also raises questions:
-
Does this mean that "sealed" types are "simple" F# types (i.e., not defined as "class types")?
Found the issue #1320: Allow types to be Sealed by default, but I think that it only proposes "class" types to be "sealed" by default (as the "simple" types already are). Then again, this may be a misinterpretation.
-
I thought I understood what the
box
operator does (even mentioned the same scenario there), but just realized that I don't know what "box
a returns value a wrapped in a .NETSystem.Object
instance" means.Does "wrapping" mean that a
box
ed "simple" F# type is redefined the same way as the original input, but as a "class type", inheriting everything fromSystem.Object
?
Please read before considering to close this question
This was intended for the trigger happy SO audience, but doesn't hurt to include it here:)
Yes, there are two questions in the title, but before closing this question, please consider my reasoning: I tried to separate and link the questions bi-directionally, but
-
an abstract answer to the first one (similar to the guide's) without examples would probably just as unhelpful without context, and
-
asking the 2nd question would inevitable duplicate efforts to define what a "sealed" type is.
Thank you!
0 comment threads