« Return to Thread: [scala] Constructor parameters for traits

[scala] Constructor parameters for traits

by Sebastien Braun :: Rate this Message:

Reply to Author | View in Thread

Hello, List.

I know that traits can not have constructor parameters, however I have not
been able to find out much about the rationale behind this restriction; my
google-fu fails me and the SLS is quiet on it (or, maybe, I just don't know
where to look for it).

For this scala code

> trait A {
>   System.out.println("Hello, World!")
> }
>
> class AImpl extends A

scalac will generate (something closely resembling) the following pseudo-Java:

> public interface A {}
>
> public class A$class {
> public static void $init$(A $this) {
> System.out.println("Hello, World!");
> }
> }
>
> public class AImpl implements A {
> public A() {
> A$class.$init$(this);
> }
> }
So, intuitively (and perhaps naïvely...), it seems to me that the compiler
should also be able to accept constructor parameters for traits:

> trait A(message: String) {
> System.out.println(message)
> }

and just tack on the arguments to the $init$ method of the trait's
implementation class:

> public interface A {}
>
> public class A$class {
> public static void $init$(A $this, String message) {
> System.out.println(message);
> }
> }

Is this a bad idea?

Cheers,

Sébastien


signature.asc (204 bytes) Download Attachment

 « Return to Thread: [scala] Constructor parameters for traits