constructor overloading with self-types

4 views
Skip to first unread message

abc123ninja

unread,
Apr 11, 2011, 12:29:04 PM4/11/11
to scala-user
Is it possible to provide constructor overloads when using self-types?

scala> trait A
defined trait A

scala> class B(val x: Int){self: A => def this() = this(2)}
<console>:6: error: too many arguments for constructor $iw: ()object
$iw
class B(val x: Int){self: A => def this() = this(2)}

If possible, how? From what I've heard when using self-types the
"this()" will refer to the "self"'s this() and thus it's not possible
- or at least not trivial.




A weird thing I came across though when mucking about is below;

scala> trait A
defined trait A

scala> class B(val x: Int){self: A => def this() = this()} //THIS (in
place of above) COMPILES
defined class B

scala> val x = new B(2) with A
java.lang.VerifyError: (class: B, method: <init> signature: ()V)
Expecting to find unitialized object on stack
at .<init>(<console>:7)
at .<clinit>(<console>)
at RequestResult$.<init>(<console>:9)
at RequestResult$.<clinit>(<console>)
at RequestResult$scala_repl_result(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:
39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:
25)
at java.lang.reflect.Method.invoke(Method.java:597)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun
$apply$17.apply(Interpreter.scala:988)
at scala.tools.nsc.Interpreter$Request$$anonfun$loadAndRun$1$$anonfun
$apply$17.apply(Interpreter.scala:988)
at ...


Should above really result in a runtime error?

Same goes for

scala> val x = new B with A
java.lang.VerifyError: (class: B, method: <init> signature: ()V)
Expecting to find unitialized object on stack


But the most weird thing is;
scala> val x = new B(1,2) with A
<console>:7: error: overloaded method constructor B with alternatives:
()B <and>
(x: Int)B
cannot be applied to (Int, Int)
val x = new B(1,2) with A


Now this somehow confirms that B after all actually _has_ overloaded
constructors!
What gives?
Reply all
Reply to author
Forward
0 new messages