user3685285
user3685285

Reputation: 6586

F# initialize objects inside struct with constructor

I have the following struct in F#:

type public Data = 
    struct
        val class1: Class1
        new() {
            class1 = new Class1()
        }
    end

But I get an error that says structs cannot have an empty constructor. Class1 is a class that has a valid default constructor, and needs to be initialized before it is used. Thus, I want class1 to call its constructor when the Data struct is created. How can I do this, or should I not be doing this at all?

Upvotes: 0

Views: 367

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

As Peter mentioned in the comments, structs cannot have constructors with no arguments. In fact, if you fix the syntax (add the = sign), the F# compiler tells you exactly this:

type public Data = 
  struct
    val class1: Class1
    new() = { class1 = new Class1() }
  end

error FS0870: Structs cannot have an object constructor with no arguments. This is a restriction imposed on all CLI languages as structs automatically support a default constructor.

Your best chance is probably to create a struct with (possibly private) constructor taking the Class1 value, and add a static method that lets you create the default instance using Data.Create():

[<Struct>]
type Data private(class1:Class1) =
  static member Create() = Data(new Class1())

You could write this using struct .. end too, but I personally prefer using the simpler object notation and just add the Struct attribute.

Upvotes: 3

Related Questions