The Artima Developer Community
Sponsored Link

Programming in Scala Forum
PrintStream

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
Otfried Cheong

Posts: 5
Nickname: otfried
Registered: Dec, 2010

PrintStream Posted: Feb 7, 2011 4:30 AM
Reply to this message Reply
Advertisement
I'm just starting to teach a (sophomore) undergraduate course on data structures using Scala, and I'm trying to put together a short introduction to Scala for my students (they know Python, some also a bit of C).

It's not easy using Scala in courses for beginners because the documentation is either very concise, or falls back on Java documentation (which is sometimes really hard to understand for students who do not know Java).

One of the rough edges seems to be PrintStream or PrintWriter. My students can write formatted text to the terminal using println, print, and printf. Now they want to write to a text file, so they create a PrintStream and call its print methods. Now, println and print work, but printf doesn't:


scala> val S = new java.io.PrintStream("test.txt")
S: java.io.PrintStream = java.io.PrintStream@19d2f6b
scala> S.println("Hello World")
scala> S.printf("%d numbers\n", 3)
<console>:7: error: type mismatch;
found : Int
required: java.lang.Object
Note: primitive types are not implicitly converted to AnyRef.
You can safely force boxing by casting x.asInstanceOf[AnyRef].
S.printf("%d numbers\n", 3)


Apparently PrintStream.printf doesn't work because PrintStream is a Java class, and the Scala compiler doesn't do the necessary boxing in this call.
But how do I explain this to my students, and what should I tell them to use instead?

Something that works well is:

scala> val S = new java.io.PrintStream("test.txt")
S: java.io.PrintStream = java.io.PrintStream@a224b5
scala> Console.withOut(S) {
| println("Hello World")
| printf("%d numbers\n", 3)
| }
scala> S.close()

But this is rather a detour.

Should there perhaps be a Scala wrapper for PrintStream?

Cheers,
Otfried

Topic: Using Java class from Scala Previous Topic   Next Topic Topic: Compilation error from SScells Spreadsheet

Sponsored Links



Google
  Web Artima.com   

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