ShawnMartin
ShawnMartin

Reputation: 282

Constraint produces "This construct causes code to be less generic..."

I am trying to use a generic with a constraint to allow access to a property of a parameter. Accessing the property inside the function produces a compile-time warning of "This construct causes code to be less generic than indicated by the type annotations. The type variable 'Item has been constrained to be type 'Foo2'."

namespace Test
type Foo = { Bar:string; NotUsed:string }
type Foo2 = { Bar:string }

module Shared =
    let inline showMeABar (item: ^Item when ^Item : (member Bar : string)) = item.Bar

Did I make a syntax mistake or is this not possible?

Upvotes: 1

Views: 299

Answers (1)

Vandroiy
Vandroiy

Reputation: 6223

Calling the getter is weird. You can do it explicitly like this:

let inline showMeABar item =
    (^Item : (member Bar : string) item)

Record labels have the weird (but useful) property that their usage with dot-notation is a hint to type inference. Hence the strange error message.

Upvotes: 4

Related Questions