Scala: a higher grade type as a type parameter

Please consider the following code snippet (it shows a simplified version of my real problem):

trait Id[Type[_]] { def id[S]: S => Type[S] } trait IdTransformer[Type[_]] { type Result[_] // depends of Type def idTransform[P]: P => Result[P] def composeWith[Other[_]](other: Id[Other]) = new Id[Result[Other]] { def id[S] = x => idTransform(other.id(x)) } } // instance example class OptionIdTransformer extends IdTransformer[Option] { type Result = Option[_] def idTransform[S] = x => Some(x) } 

Here I have an Id property that defines a function that transfers the value to a type, and the IdTransformer attribute determines how to add new logic to the id operation. I want to use them the way

 Transformer1.composeWith(Transformer2.composeWith(...(idInstance))) 

But when I compile the code, I get error messages

 type Other takes type parameters 

and

 IdTransformer.this.Result[<error>] takes no type parameters, expected: one 

in the comp WithWith method, although Result [Other] must be of a higher type and must accept one type parameter. Please explain the reason for the errors and if there is a workaround.

+4
source share
1 answer

You are trying to create a higher type with two other hihgher types. To do this, you need a trick like a lambda .

 trait IdTransformer[Type[_]] { type Result[_] // depends of Type def idTransform[P]: P => Result[P] def composeWith[Other[_]](other: Id[Other]) = new Id[({type λ[α] = Result[Other[α]]})#λ] { def id[S] = x => idTransform(other.id(x)) } } 
+1
source

Source: https://habr.com/ru/post/1483351/


All Articles