fun main(args: Array<String>) {
val bookShelf = BookShelf(4)
bookShelf.appendBook(Book("Around the world in 80 days"))
bookShelf.appendBook(Book("Bible"))
bookShelf.appendBook(Book("Cinderella"))
bookShelf.appendBook(Book("Daddy-Long-Legs"))
val it = bookShelf.iterator()
while (it.hasNext()) {
val book = it.next() as Book
println(book.getName())
}
}
class Book(private val name:String){
fun getName() = name
}
class BookShelf(maxSize: Int): Aggregate {
private val books: Array<Book> = Array<Book>(maxSize){ _ -> Book("")}
private var last = 0
fun getBookAt(index: Int): Book {
return books[index]
}
fun appendBook(book: Book) {
this.books[last] = book
last++
}
fun getLength(): Int {
return last
}
override fun iterator(): Iterator {
return BookShelfIterator(this)
}
}
class BookShelfIterator(private val bookshelf:BookShelf):Iterator{
private var index: Int = 0
override fun hasNext(): Boolean {
return index < bookshelf.getLength()
}
override fun next(): Any {
val book = bookshelf.getBookAt(index)
index++
return book
}
}
interface Aggregate{
abstract fun iterator():Iterator
}
interface Iterator{
abstract fun hasNext(): Boolean
abstract fun next():Any
}
hyuki@hyuki.com This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
コメント