The Artima Developer Community
Sponsored Link

Programming in Scala Forum
Can I override a field with a method?

2 replies on 1 page. Most recent reply: Jan 20, 2009 4:53 PM by Haixu Huang

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 2 replies on 1 page
Haixu Huang

Posts: 6
Nickname: regular
Registered: Oct, 2008

Can I override a field with a method? Posted: Jan 19, 2009 1:25 AM
Reply to this message Reply
Advertisement
See topic.


Bill Venners

Posts: 2284
Nickname: bv
Registered: Jan, 2002

Re: Can I override a field with a method? Posted: Jan 19, 2009 4:56 PM
Reply to this message Reply
No, but you can do it the other way around. You can override a parameterless method with a val field.


scala> class Super {
| private val generator = new Random
| def length: Int = generator.nextInt
| }
warning: there were deprecation warnings; re-run with -deprecation for details
defined class Super

scala> val a = new Super
a: Super = Super@9babc

scala> a.length
res4: Int = 159125958

scala> a.length
res5: Int = 1789171216

scala> a.length
res6: Int = 1404266232

scala> class Sub extends Super {
| override val length: Int = 7
| }
defined class Sub

scala> val b = new Sub
b: Sub = Sub@51e3be

scala> b.length
res7: Int = 7

scala> b.length
res8: Int = 7


The reason you can't override a field with a method is that a method can produce a different value each time, though it isn't required to. Thus a val that always produces the same value can be a valid "implementation" of a method. But if the superclass has a val, then that's supposed to always be the same value, and so it wouldn't be safe to let people override them with defs that could return a different value each time (as well as have side effects each time).

Haixu Huang

Posts: 6
Nickname: regular
Registered: Oct, 2008

Re: Can I override a field with a method? Posted: Jan 20, 2009 4:53 PM
Reply to this message Reply
OK, I got it. Thanx. :)

Flat View: This topic has 2 replies on 1 page
Topic: How to show the data grids view in a tooltip? Previous Topic   Next Topic Topic: Is there a way to

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use