variable parameter trouble

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

variable parameter trouble

Stefan Matthias Aust
The Scala 2.1.3 compiler compiles this code just fine:

  package test;

  object test {
    class A
    class B

    def m(a: A,  b: B*) = b.toArray
    def m(a: A*, b: B ) = a.toArray
    def m(a: A*, b: B*) = a.toArray
  }

But I cannot call the second or third method variant. If it is only
possible that the last parameter can be a variable argument parameter
(and so it seems), the compiler should not allow the other definitions.

If I use the second definition and m(new B()), I get the error "wrong
number of arguments". If I call m(new A(), new B()), I get the error
"type mismatch; found "A"; required "A*".

My guess is that you allow the other definitions because if you pass a
*-parameter to another method, it can be at any position. Still, it's
irritating IMHO.

--
Stefan Matthias Aust

Reply | Threaded
Open this post in threaded view
|

Re: variable parameter trouble

Stefan Matthias Aust
Addendum 1: If I want to iterate the values, I cannot use

  parameters.map(...)

as with arrays or lists, but need to use

  parameters.elements.map(...)

this violates IMHO the principle of the minimal surpise.

Addendum 2: Why don't arrays support isEmpty as lists do? Actually, Seq
should probably do because it implements length. Or remove isEmpty from
List... And if I can concat lists with :::, I'd like to use that
"operator" also on arrays.

Addendum 3: I really need something like Smalltalk's #doWithIndex: or
Ruby's each_index. Something like

  class Array[A]...
    def mapInto[B](f: A => B, arr:Array[B], offset: Int = 0) = {
     elements.foreach(e => arr(offset) = f(e); offset = offset + 1)
    }

would also do the trick.

--
Stefan Matthias Aust

Reply | Threaded
Open this post in threaded view
|

Re: variable parameter trouble

Lex Spoon
In reply to this post by Stefan Matthias Aust
Stefan Matthias Aust <[hidden email]> writes:

> The Scala 2.1.3 compiler compiles this code just fine:
>
>   package test;
>
>   object test {
>     class A
>     class B
>
>     def m(a: A,  b: B*) = b.toArray
>     def m(a: A*, b: B ) = a.toArray
>     def m(a: A*, b: B*) = a.toArray
>   }
>
> But I cannot call the second or third method variant. If it is only
> possible that the last parameter can be a variable argument parameter
> (and so it seems), the compiler should not allow the other definitions.

This is not allowed, according to my recollection and to the spec.
The spec says (page 31):

    The last value parameter of a parameter section may be suffixed by
    "*", e.g. (..., x:T*).

It then goes on to talk about what * types mean, exclusively talking
about them as the last parameter of a method.  So, it's a bug that
this was accepted.


-Lex