Why is an accessor required when defining an assignment method?

90 views
Skip to first unread message

Owen

unread,
Jan 11, 2016, 12:55:31 PM1/11/16
to scala-debate
In

  object foo {
    def x_=(x: Int) { }
  }
  
  foo.x = 2

there is an error, but in

  object foo {
    def x_=(x: Int) { }
    def x = 3
  }
  
  foo.x = 2

there is not. Could this restriction be lifted?

som-snytt

unread,
Jan 15, 2016, 1:35:21 PM1/15/16
to scala-debate

Requiring the member selection to type check affects implicit conversions.

I'm not sure what I expected here:

scala> class C { def f = 42 }
defined class C

scala> class D { def f_=(i: Int) = println(s"set $i") }
defined class D

scala> class E
defined class E

scala> implicit def cv(d: C): D = new D
warning: there was one feature warning; re-run with -feature for details
cv: (d: C)D

scala> (new C).f = 5
set 5
new C().f: Int = 42

scala> implicit def cv2(d: E): C = new C
warning: there was one feature warning; re-run with -feature for details
cv2: (d: E)C

scala> (new E).f = 5
<console>:16: error: value f_= is not a member of C
       (new E).f = 5
               ^

Owen

unread,
Jul 6, 2016, 11:41:49 AM7/6/16
to scala-debate
Huh. That's really weird.

I suppose implicit conversions and mutability will always be a little odd together because implicit conversion naturally creates temporary objects that thwart mutable state.
Reply all
Reply to author
Forward
0 new messages