scalaimplicit-conversionimplicitscala-3existential-type

How to define a implicit (given) Conversion for Generic Types?


I want to use the Scala 3 Implicit Conversion.

I have the following construct that I want to migrate:

  implicit def toTesterObjectScenario[In <: Product](
                                   decisionDmn: DecisionDmn[In, _]
                                ): DmnTesterObject[In] =
    DmnTesterObject(decisionDmn, defaultDmnPath(decisionDmn.decisionDefinitionKey))

I tried:

  given Conversion[DecisionDmn[_ <: Product, _], DmnTesterObject[_ <: Product]] with
    def apply(decisionDmn: DecisionDmn[_ <: Product, _]): DmnTesterObject[_ <: Product] =
      DmnTesterObject(decisionDmn, defaultDmnPath(decisionDmn.decisionDefinitionKey))

This compiles but does not work when running:

Exception in thread "main" java.lang.NoSuchMethodError: 'camundala.dmn.DmnTesterConfigCreator$DmnTesterObject camundala.dmn.DmnTesterConfigCreator.toTesterObjectScenario$(camundala.dmn.DmnTesterConfigCreator, camundala.bpmn.DecisionDmn)'
    at valiant.bpmn.dmn.BpmnDmnTester$.toTesterObjectScenario(BpmnDmnTester.scala:11)

This does not even compile:

  given Conversion[DecisionDmn[_ <: Product, _], DmnTesterObject[_ <: Product]] with
    def apply[In <: Product](decisionDmn: DecisionDmn[In, _]): DmnTesterObject[In] =
      DmnTesterObject(decisionDmn, defaultDmnPath(decisionDmn.decisionDefinitionKey))

Is this not possible or how it is done?


Solution

  • You need a given instance of type Conversion[DecisionDmn[In, _], DmnTesterObject[In] where In <: Product.

    This is how you can add a type parameter to a given instance:

    given [In <: Product]: Conversion[DecisionDmn[In, _], DmnTesterObject[In]] with
      def apply(decisionDmn: DecisionDmn[In, _]): DmnTesterObject[In] = ???