The Artima Developer Community
Sponsored Link

Programming in Scala Forum
unit value: () or {}

1 reply on 1 page. Most recent reply: Feb 1, 2008 12:57 PM by Bill Venners

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 1 reply on 1 page
David Biesack

Posts: 8
Nickname: djb
Registered: Jan, 2008

unit value: () or {} Posted: Jan 31, 2008 12:49 PM
Reply to this message Reply
Advertisement
Programming in Scala says on p 129

"Technically, it does return the unit value, written ()"

but ScalaReference.pdf (Version 2.6, Dec 19, 2007) says on p. 38

"{} if T is Unit,"

and on p. 46

"... Special syntax exists for procedures, i.e. functions that return the Unit value {}."

but then says

"the unit value ()" on p 77, 135

Which is correct?


Bill Venners

Posts: 2284
Nickname: bv
Registered: Jan, 2002

Re: unit value: () or {} Posted: Feb 1, 2008 12:57 PM
Reply to this message Reply
Both are valid, but () is idiomatic:


scala> val a = ()
a: Unit = ()

scala> val b = {}
b: Unit = ()


In general, you can use curly braces in many places you can use parens in Scala. I'm not sure at this point of the exact rules. I didn't know until this post that you could use them for the unit value. I do know you can use them for enclosing argument lists.


scala> println("hi")
hi

scala> println{"hi"}
hi


One thing this enables is methods that look like control constructs. In ScalaTest, you can do this:


expect(List(1, 2, 3)) {
1 :: List(2, 3)
}


That stuff between the curly braces is a second set of args. You could also write it:


expect(List(1, 2, 3))(1 :: List(2, 3))


But the curly brace form makes it look more like a control construct.

Flat View: This topic has 1 reply on 1 page
Topic: extending multiple traits. Previous Topic   Next Topic Topic: Please make the list of suggestion browseable

Sponsored Links



Google
  Web Artima.com   

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