. .


ST 4U 179: Read Streams in Smalltalk

January 9, 2012 8:33:59.246

Today's Smalltalk 4 You continues looking at the basic Smalltalk class libraries in VA Smalltalk - today it's the Stream libraries, focusing on reading. If you have trouble viewing it here in the browser, you can also navigate directly to YouTube. To watch now, click on the image below:


If you have trouble viewing that directly, you can click here to download the video directly. If you need the video in a Windows Media format, then download that here.

You can also watch it on YouTube:

Today we'll look at the Stream class hierarchy, focusing on read streams. To get started, we want to browse the Stream hierarchy, in order to get a full picture of the local and inherited APIs:/p>


We are going to focus on the API methods (as per the ANSI specification, and experiment with a few simple examples in a workspace. The workspace code we'll use follows:

"read stream on a collection"
array := #(1 2 3 4 5 6 7 8 9 10).
stream := array readStream.

"get next item"
oneItem := stream next. 1

"get next 3"
nextThree := stream next: 3. (2 3 4)

"up to end"
rest := stream upToEnd. (5 6 7 8 9 10)

"set back to start"
stream reset.

"now peek - get next item, don't move position"
pos := stream position. 0
peeked := stream peek. 0
pos2 := stream position.  0

"skip first 3, get 4th"
stream skip: 3.
fourth := stream next. 4

You may be wondering about the text printed after each line; that's the result of doing a Display on each set of code. Try it yourself, and see if it all works the same way

Most of the examples work with streams that are positionable - i.e., there's a cursor into the stream, and we can freely move the cursor back and forth. That's true of internal streams and of file streams - but not of things like streams over a socket. Take a look at class PositionableStream and the APIs defined in it:

Positionable Streams

Here's a screen capture of the workspace after we've tried each line:


The most important reading methods to understand are:

  • #next - get the next element from the stream
  • #next: - get the next N elements from the stream
  • #upToEnd - get the rest of the elements on the stream
  • #reset - reset the position back to the start
  • #peek - peek ahead one element without moving the cursor

It's worth trying a few experiments of your own - and notice that streams are not just about text. You can stream over any collection in Smalltalk, as our example above shows.

Need more help? There's a screencast for other topics like this which you may want to watch. Questions? Try the "Chat with James" Google gadget over in the sidebar.

Technorati Tags: , ,

[st4u179-iPhone.m4v ( Size: 7006057 )]

posted by James Robertson

 Share Tweet This