简体   繁体   中英

F# This expression should have type 'unit', but has type 'bool'

I have the following code

if somecondition then
  myobj.Property1 = match myobj.Property1 with
                       | null -> SomePropertyType ()
                       | p -> p

What I am trying to do is to see if myobj.Property1 is null, if it is not then leave it alone otherwise create a new object of type SomePropertyType and assign it.

Problem is, I am getting a

This expression should have type 'unit', but has type 'bool'

And what should I do If I had to put multiple of those myobj.Property1 .... statements under that if ?

You are comparing two values (using = ) so the return type will be bool , but if you have an if without else the compiler expect unit as return type.

I guess you intended to assign the value to the property, use <- instead:

if somecondition then
    myobj.Property1 <- match myobj.Property1 with ...

Anyway if you want to check for null to assign a default value you don't need a match , an if then is enough:

if somecondition then
    if (myobj.Property1 = null) then myobj.Property1 <- SomePropertyType ()
    ...

UPDATE

You can "merge" both if .. then to a single match :

match (somecondition, myobj.Property1) with
| true, null -> myobj.Property1 <- SomePropertyType ()
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM