DotNetRussell
DotNetRussell

Reputation: 9857

ContainsKey returns unit and not bool?

It's odd to me that the following code throws a compile time error. I'm not sure why ContainsKey is returning unit. The documentation says it returns bool.

open System.Collections.Generic    

let mydict = new Dictionary<string,'a>()

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] = newkey

error FS0001: This expression was expected to have type 'bool' but here has type 'unit'

Am I missing something here?

Upvotes: 3

Views: 105

Answers (1)

Lee
Lee

Reputation: 144136

if is an expression so both branches must have the same type. If the else branch is not specified an empty one of type unit is inserted. This means your then branch must also have type unit. However mydict.["mykey"] = newkey has type bool. If you want to insert a new value for mykey you should use <- instead of =:

if(mydict.ContainsKey "mykey") then
    mydict.["mykey"] <- newkey

Upvotes: 6

Related Questions