Last active
August 29, 2015 13:57
-
-
Save 544/9460150 to your computer and use it in GitHub Desktop.
Scalaのクラスについて ref: http://qiita.com/544/items/774e9a0bfed5507fad14
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** class and instance sample */ | |
class SimpleClass(id:String) { | |
// インスタンス化のタイミングで実行される。 | |
println("create SimpleClass id:" + id) | |
// 補助コンストラクタ | |
def this() { | |
// 先頭で基本コンストラクタを呼び出す必要がある。 | |
this("dummy"); | |
println("create by sub contracter") | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** method sample */ | |
class SimpleClass2 { | |
def sayHello(name:String):Unit = { | |
println("hello, " + name + "!!"); | |
} | |
// 引数が異なればオーバーロード可能 | |
def sayHello(times:Int):Unit = { | |
println("hello," * times); | |
} | |
def sayHello(name:String, times:Int):Unit = { | |
println(( "hello," * times ) + " " + name + "!!"); | |
} | |
// 戻り値が異なるメソッドは定義できない。 | |
/* 以下はコンパイルエラーになる。 | |
def sayHello(times:Int):String = { | |
"hello" * times; | |
} | |
*/ | |
// 引数にデフォルト値を定義 | |
def sayBye(name:String, times:Int = 3):Unit = { | |
println( ("Bye,"*times) + " " + name + "!!" ); | |
} | |
// 暗黙の引数を定義 | |
def greet(implicit name:String):Unit = { | |
println( "Hi! " + name ); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** field sample */ | |
class SimpleClass3 { | |
// アクセサを独自実装するため、privateとする。 | |
private var _id:Int = _; // _ は型のデフォルト値 | |
// getter | |
def id:Int = { | |
println("call getter!"); | |
_id; | |
} | |
// setter | |
def id_= (id:Int) = { | |
println("call setter!"); | |
_id = id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
typo