1

I can define a function or a method in Scala as below:

def myMethod: Boolean = true

or

val myBoolVal = () => true

Which one is preferred any why? Is defining a myMethod has compiler benefits? Any suggestions?

joesan
  • 13,963
  • 27
  • 95
  • 232
  • 1
    The first expression defines a method, the second expression defines an immutable pointer to a lambda, which evaluates to `true` and takes no arguments. For sanity, I would stick to the first definition, if you truly are interested in this, check the byte code the two expressions compile to. – Johan S Jan 28 '16 at 14:58
  • I don't know who down voted this question. This is definitely not a silly question! – joesan Jan 28 '16 at 14:59
  • They are also called differently, `myMethod //> true` and `myBoolVal() //> true`. Just two completely different entities. Relative equivalent of the first would be `val myBooleanVal = true`. Unless you need a lambda I would stick with `def` or `val myBooleanVal = true`. – Victor Moroz Jan 28 '16 at 16:05
  • I didn't downvote, but while not silly, it's also a duplicate... See http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala and http://stackoverflow.com/questions/4437373/use-of-def-val-and-var-in-scala?rq=1 (which is linked to from this question - it was probably suggested to you when you wrote the question?) – The Archetypal Paul Jan 28 '16 at 16:06

0 Answers0