How to express (implicit conv: String => A) as a view bound

432 Views Asked by At

I am asking myself what would be the view bound equivalent to

(implicit conv: String => A)

My first attempt was to simply declare the type parameter A as follows:

[String <% A]

But the Scala compiler complains with "not found: type A".

Any suggestions?

2

There are 2 best solutions below

1
Daniel C. Sobral On BEST ANSWER

That is not a view bound. A view bound says that a type parameter A is bounded in that it can be viewed (converted to) as a type B. What you have inverted type and type parameter, so it doesn't qualify.

To make things more clear, a bound is a limit on a "free" type -- a type parameter. For example:

type A <: String // A has an upper bound
type A >: String // A has a lower bound

So a view bound is also a limit -- one imposed through a very different mechanism. As such, it can only be imposed on a type parameter, not on a type.

Surely, saying String => A must exist is also a kind of bound, but not one that has a name or syntactic sugar for.

2
Kipton Barros On

-- Revised post --

The syntax [B <% A] actually binds a new type B. So

class Foo[A, String <% A]

is equivalent to

class Foo[A, String](implicit $conv: String => A)

where String is an arbitrary type parameter, not the class you're thinking of.

I think the named implicit conversion is probably your best option,

class Foo[A](implicit conv: String => A)

where now the type of String is not shadowed.

Summary: view bounds are useful as conversions from the introduced type parameter, not to the type parameter.