bstack
bstack

Reputation: 2528

How do I create a dictionary in f# where value is "generic"

I am an f# beginner.

I want to create some sort of dictionary where the following applies:

  1. The key is a string
  2. The value is a generic object of some sort

E.g. consider the following f# script extract that utilizes a c# library where two c# classes (student and teacher) inherit from a common base c# class Person:

#r @"D:\Temp\MyCSharpLib.dll"

open MyCSharpLib

let student = Student() // Student inherits from Person
let teacher = Teacher() // Teacher inherits from Person

let eventStream = Map.empty.Add("Key1", student).Add("Key2", teacher)

I have attempted to use a Map to do this but I get an error as the compiler expects all values to be of type Student.

Is there any way to do this in f#?

Upvotes: 2

Views: 166

Answers (1)

Tarmil
Tarmil

Reputation: 11362

Indeed, in this case F# cannot guess that for the initial map you actually wanted a Map<string, Person> and not a Map<string, Student>. You can indicate it explicitly:

let eventStream = Map.empty<_,Person>.Add("Key1", student).Add("Key2", teacher)

Upvotes: 4

Related Questions