Monday 3 October 2011

F# - Abstract class

It's possible to create an abstract class, but it's not obvious how to do it. You need to create a type, as normal. Then place an abstract method declaration within. At this point, though, the compiler still grumbles. Now you have to tag the type with [<AbstractClass>].

First attempt:


> type C =
inherit Exception
new () = {inherit Exception()}
abstract print : unit -> unit
;;

type C =
-----^

stdin(14,6): error FS0365: No implementation was given for 'abstract member C.print : unit -> unit'


Now apply the annotation and, hey presto, the compiler responds with:


type C =
class
inherit Exception
new : unit -> C
abstract member print : unit -> unit
end


But why the compiler can't work it out for itself I don't know.

No comments:

Post a Comment