Reputation: 115
In C# i can declare uninitialized variables that are then later assigned to in various methods of the class. For example, in an NUnit test i can declare a typed variable that is only initialized in a setup method and then repeatedly used in the various tests.
private MyTestClass sut;
public Setup()
{
sut = new MyTestClass();
etc.
}
public FirstTest()
{
sut.DoSomeWork(1);
}
public SecondTest()
{
sut.DoSomeWork(2);
}
I would like to do the equivalent in F#. However according to this and others, unassigned 'variables' is just not the done thing in F#.
In the case of my F# tests, the tests are not sitting in any type, just within a module so [<DefaultValue>] val
won't work.
Using mutable
just doesn't feel right as that seems to be the option of last resort for F# coders.
Since idomatic F# shouldn't require unassigned values, what is the "correct" way of getting around this problem?
Upvotes: 2
Views: 183
Reputation: 12184
You could use lazy
:
let sut = lazy (new MyTestClass())
lazy
defers the execution of an expression until the result is needed. Subsequent requests for the lazy value don't require it to be recomputed, it simply returns the stored result from last time.
Then you can do:
let ``First test``() =
sut.Force().DoSomeWork(1)
let ``Second test``() =
sut.Force().DoSomeWork(2)
This could be appropriate if initialisation is expensive and you don't wish to repeat it.
Upvotes: 1
Reputation: 10624
You can use functions and values. There is no need to declare unassigned variables.
let makeTestClass() =
MyTestClass()
// etc.
let ``First test``() =
let sut = makeTestClass()
sut.DoSomeWork()
let ``Second test``() =
let sut = makeTestClass()
sut.DoSomeWork()
Upvotes: 5