3

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?

Tim Friske
  • 2,012
  • 1
  • 18
  • 28
  • 3
    Where are you getting type A from? Does (implicit conv: String => A) work? Please post all the relevant code. – Lex Aug 23 '11 at 21:28

2 Answers2

8

-- 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.

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Kipton Barros
  • 21,002
  • 4
  • 67
  • 80
  • Thanks Lex and Kipton for your prompt reply. @Kipton: I thought it is feasible to declare the type parameter `A` with the view bound in one go. Something like `class Foo[String <% A]`. Isn't that possible? – Tim Friske Aug 23 '11 at 23:17
  • 1
    You can do `class Foo[A, String <% A]`, but I just realized this is introducing a new type `String` that shadows the usual `String` class. I rewrote my answer. – Kipton Barros Aug 23 '11 at 23:51
2

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.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • That's a good explanation. I think Tim Friske was looking for an "inverted" view bound: `[A >% String]` (pseudo-code). Scala doesn't have this, just write out the implicit conversion by hand. – Kipton Barros Aug 24 '11 at 23:24