Jeff
Jeff

Reputation: 237

Type alias vs lambda type

Can anybody explain the pros/cons of

type VNel[+A] = ValidationNel[String, A]
x.sequence[VNel, ....

vs

x.sequence[({ type l[a] = ValidationNel[String, a] })#l, ....

From what I understand, using structural types incurs a runtime performance hit of having to use reflection.

Upvotes: 2

Views: 375

Answers (2)

lmm
lmm

Reputation: 17431

They are mostly equivalent - use whichever you find clearer. IMO the type alias is usually more readable. In the context of a trait (or class) written to be extended, the type lambda can be clearer as it prevents overriding the type, but this is very much an edge case.

Accessing values defined in a structural type in ordinary code would indeed incur the cost of using reflection. But in a type lambda the structural type is only used as a generic type parameter, which will be erased at runtime. So there will be no runtime performance impact.

If you're making extensive use of type lambdas, you might like to consider the kind-projector plugin, which provides a more convenient syntax (and avoids the misleading visual resemblance to a structural type).

Upvotes: 1

Johnny Everson
Johnny Everson

Reputation: 8601

Type lambda is a way to express complex types inline.

Type alias is way create an identifier for a type. It can be a complex type or be as simple as type UserId = Int. It is useful when you start needing a complex type more than once or you want to simplify a complex signature by breaking it in parts.

Neither type lambdas and type alias are structural typing. but rather a way to express types.

For more details on type lambdas: https://stackoverflow.com/a/8737611/547564

Upvotes: 3

Related Questions