import java.lang.RuntimeException
fun main(args: Array<String>) {
try {
println("Making root entries...")
val rootdir = Directory("root")
val bindir = Directory("bin")
val tmpdir = Directory("tmp")
val usrdir = Directory("usr")
rootdir.add(bindir)
rootdir.add(tmpdir)
rootdir.add(usrdir)
bindir.add(File("vi", 1000))
bindir.add(File("latex", 2000))
rootdir.printList()
println("")
println("Making use entries...")
val yuki = Directory("yuki")
val hanako = Directory("hanako")
val tomura = Directory("tomura")
usrdir.add(yuki)
usrdir.add(hanako)
usrdir.add(tomura)
yuki.add(File("diary.html", 100))
yuki.add(File("Composite.java", 200))
hanako.add(File("memo.tex", 300))
tomura.add(File("game.doc", 400))
tomura.add(File("junk.mail", 500))
rootdir.printList()
} catch (e: FileTreatmentException) {
e.printStackTrace()
}
}
abstract class Entry{
abstract fun getName(): String
abstract fun getSize(): Int
open fun add(entry: Entry) :Entry{
throw FileTreatmentException()
}
fun printList(){
printList("")
}
//protectedにするとなぜかDirectoryのPrintList内で呼び出せない
abstract fun printList(prefix: String)
override fun toString() = "${getName()}(${getSize()})"
}
class File(private val name: String, private val size: Int):Entry(){
override fun getName(): String {
return name
}
override fun getSize(): Int {
return size
}
override fun printList(prefix: String) {
println("${prefix}/${this}")
}
}
class Directory(private val name: String):Entry(){
private var directory = arrayListOf<Entry>()
override fun getName() = name
override fun getSize(): Int {
var size = 0
val it = directory.iterator()
while (it.hasNext()) {
val entry = it.next()
size += entry.getSize()
}
return size
}
override fun add(entry: Entry): Entry {
directory.add(entry)
return this
}
override fun printList(prefix: String) {
println("${prefix}/${this}")
val it = directory.iterator()
while (it.hasNext()) {
val entry = it.next()
entry.printList("${prefix}/${name}")
}
}
}
//コンストラクタの引数も規定値構文出来る
class FileTreatmentException(msg:String = "") : RuntimeException(msg){
}
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.
コメント