I have some simple code that I just can’t get to compile. (It compiled once but didn’t work properly and, after messing around with it a lot, I can’t now remember how it looked when it compiled.)
I know I will be doing something stupid but I’ve tried so many variants of this code that I can’t remember which way round I should be looking now.
The code, as it currently stands, is as follows:
open System
type IMyThing =
abstract member GetNumberAsString : unit -> string
abstract member ChangeNumber : unit -> unit
[<AbstractClass>]
type BaseThing(initialNumber : int) =
let mutable theNumber = initialNumber
interface IMyThing with
member _.GetNumberAsString() = theNumber |> string
member _.ChangeNumber() = ()
type RandomThing(initialNumber : int) =
inherit BaseThing(initialNumber)
override this.ChangeNumber() =
let rnd = System.Random.Shared.Next()
printfn "Random: Changing number to %A" rnd
theNumber <- rnd
let randomThing = new RandomThing(7) :> IMyThing
let before = randomThing.GetNumberAsString()
do randomThing.ChangeNumber()
let after = randomThing.GetNumberAsString()
What I want is to have BaseThing (which should not be instantiable) define ‘something’ which stores a number (preferably not available outside of BaseThing or dervied classes) which can then be modified by the derived class instances (via ChangeNumber) and then reported on in the exact same way (via GetNumberAsString) in each derived class instance.
I can’t seem to be able to tell the compiler to override the BaseThing version of ChangeNumber. (I don’t particularly want that useless member in BaseThing but, as far as I know, I have to give it something.)
I’ve tried all kind of variants, making things abstract, trying default (which I could never get to work), overrides, using ‘this.’, or not using ‘this.’, using a property (but that was causing other problems), etc. etc.
I’ve looked at a whole lot of blog posts, and Stack Overflow questions, the Microsoft documentation, and fsharpforfunandprofit, but can’t seem to get this working.
What stupid thing(s) am I doing wrong?