0

Can't figure out why this does not work:

def f[A: Double](x: A) = x / 4 // error: "Double does not take type parameters"

println(f(87.7))

While this one works:

def f[A <: Double](x: A) = x / 4

println(f(87.7))

The only difference is that in the first case I just specify particular type, and in the second I define type upper bound.

kiritsuku
  • 52,967
  • 18
  • 114
  • 136
Vadim Samokhin
  • 3,378
  • 4
  • 40
  • 68

2 Answers2

3

That's because [A: Double] is not a correct way to define a type parameter. This form is applicable to define a class manifest context bound (new in Scala 2.8 - thanks @mhs for the link); however, the ClassManifest[T] type used to represent context bounds is a parameterized type, so Double is not fit as a class manifest.

Note though that context bounds and manifests were introduced to solve the problem of generic array creation, so there is no point using one here, as your function - as it is shown above - has nothing to do with arrays.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
  • A context bound has nothing to do with manifests. It is the other way: manifests can be used in context bounds. In the question, there are no manifests used, nor are they expected there. The asker only mixed their syntax with type ascription. – kiritsuku Jan 07 '13 at 13:27
2

When a formal type parameter has the form of the one in this definition:

def floob[Glorp : Fleeb](arg1: Glorp): Swish = ...

... it is merely syntactic sugar for this definition:

def floob[Glorp](arg1: Glorp)(implicit i1: Fleeb[Glorp]): Swish = ...

This is called a context bound.

This explains why you're getting a diagnostic about Double not taking type parameters.

Because this use of the single colon is entirely unrelated the one used in type annotations and type ascriptions, I uniformly write context bounds with a space on both sides of the colon and never write type annotations or type ascriptions with a space on the left (except when required, when the name to the left is punctuation rather than alphanumeric).

Randall Schulz
  • 26,420
  • 4
  • 61
  • 81