The Artima Developer Community
Sponsored Link

Programming in Scala Forum
Functions and Closures: withPrintWriter

0 replies on 1 page.

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 0 replies on 1 page
Jeff Heon

Posts: 40
Nickname: jfheon
Registered: Feb, 2005

Functions and Closures: withPrintWriter Posted: Jan 29, 2008 6:19 PM
Reply to this message Reply
Advertisement
I've been looking at the withPrintWriter example, and I can't figure out how the print("today is") and println(new java.util.Date) statements would apply to the writer instead of just being sent to the console (which is what happens if I try the example in the interpreter.)

def withPrintWriter(f: File, operation: PrintWriter => Unit) {
  val writer = new PrintWriter(f)
    try {
      operation(writer)
    } finally {
      writer.close()
    }
}

Given such a method, you can use it as follows:
withPrintWriter(someFile, writer => {
  print("today is ")
  println(new java.util.Date)
})


Unless I rewrite it this way:
withPrintWriter(someFile, writer => {
  writer.print("today is ")
  writer.println(new java.util.Date)
})


Is there a better way to do it?

By the way, I really like the book! Kudos!

This chapter in particular really made me see what is different between Scala and a plain OO language.

Topic: Chapter 17, Section 4 Previous Topic   Next Topic Topic: Chapter 11, page 232, precedence method

Sponsored Links



Google
  Web Artima.com   

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