3

Possible Duplicate:
why use def and val in Scala or vice versa

Obviously, when there are arguments, if the value depends upon mutable objects, or the value depends upon a trait member, one has to use def. And if the expression could throw an exception, one can't use val. But what if neither is the case? More specifically, is there ever a reason to use def in such situations? Is it preferable to use val (when the expression won't throw an exception) and lazy val (when the expression could throw an exception)?

For example:

class FifthElement(seq: Seq[Element]) {
  def hasFifthElement = seq.length > 5 // is it better to use val than def?
  def fifthElement = seq(5) // is it better to use lazy val than def?
}
Community
  • 1
  • 1
Noel Yap
  • 18,822
  • 21
  • 92
  • 144
  • Check http://stackoverflow.com/questions/9449474/def-vs-val-vs-lazy-val-evaluation-in-scala – Santosh Gokak Nov 08 '12 at 16:49
  • http://stackoverflow.com/users/135589/jesper, http://stackoverflow.com/users/465304/sschaef, http://stackoverflow.com/users/1836/matthew-farwell, http://stackoverflow.com/users/372283/dave-griffith, http://stackoverflow.com/users/3834/graviton, I don't see how this question is a duplicate of the other questions. It asks when to use val, lazy val, and def, not what their differences are. Many of the other posts also mention only two of the three. – Noel Yap Nov 09 '12 at 14:35

0 Answers0