case classes default parameters may have different meaning in constructor and companion object apply method

瀏覽次數:177 次
跳到第一則未讀訊息

Didier Dupont

未讀,
2014年11月5日 晚上7:41:562014/11/5
收件者:scala-l...@googlegroups.com
Following a question on stack overflow : http://stackoverflow.com/q/26767525/754787, and my answer http://stackoverflow.com/a/26769056/754787

When there are default arguments in a case class, say

case class A(x: X = expr)

then it causes, according to SLS 5.3.2, a factory method def apply(x: X): A = expr to be generated in the companion object of A.

It is possible that the companion object of A contains some definitions that will cause expr to have a different meaning inside and outside the object. It may compile only on one side, fail to compile on both sides for different reasons, or compile on both side, but with different meanings.

For instance :

case class A(b:B = bb)

case class B(i: Int, j: Int)

object bb extends B(3, 4)

object A {

val bb = new B(7, 2)
}

println(A())
println(new A())


This code will print

A(B(7,2))
A(B(3,4))

I also checked that if it fails to compile inside and outside for different reasons, the compiler gives two error message, and if it fails to compile either inside or outside, the code does not compile.

I believe the present behavior is in line with the specification. Still, it was not discussed in the SID for default arguments : http://docs.scala-lang.org/sips/completed/named-and-default-arguments.html, and maybe that was an oversight

Maybe it could be reconsidered (not sure which side I would favour then), or maybe it could make it into the scala puzzlers :)

Thanks

Didier Dupont

Jason Zaugg

未讀,
2014年11月5日 晚上7:57:012014/11/5
收件者:scala-l...@googlegroups.com
Good puzzler indeed! I have added this to, SI-8884, a ticket that discusses the broader issue of hygienic binding in our implementation of case class synthetic methods. From Lukas' comment on that ticket, the situation has improved in Martin's research compiler, Dotty.

-jason

Andrew Phillips

未讀,
2014年11月6日 清晨7:11:292014/11/6
收件者:scala-l...@googlegroups.com、di...@free.fr
> or maybe it could make it into the scala puzzlers :) 

I think it most certainly will ;-) If you'd like to contribute [1], that would be great - otherwise, I'll try to put together a proposal and ping for comments.

Thanks!

ap

回覆所有人
回覆作者
轉寄
0 則新訊息