Reputation: 1392
I have the following skeleton of code:
type MyException<'T> () =
inherit Exception()
type IMyInterface =
abstract member Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> : string -> int
type MyClass =
interface IMyInterface with
member this.Method s =
let i = s.IndexOf "a"
if i = -1 then raise (new MyException<'T> ())
i
However, I am getting the following message:
This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrained to be type 'obj'.
and when compiled, obj
is passed to MyException instead of 'T
.
I need to have the above type constraints on IMyInterface.Method
, and also need to pass the type passed into MyException
in MyClass.Method
. How can I accomplish this?
Upvotes: 0
Views: 70
Reputation: 4280
I think you have to parametrise MyClass
:
type MyClass<'T> =
interface IMyInterface with
member this.Method s =
let i = s.IndexOf "a"
if i = -1 then raise (new MyException<'T> ())
i
or repeat constraints on your method:
type MyClass =
interface IMyInterface with
member this.Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> s =
let i = s.IndexOf "a"
if i = -1 then raise (new MyException<'T> ())
i
Upvotes: 5