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?