開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 8(nulls and exceptions - Safe and Sound)、BE the Compiler(229)の解答を求めてみる。
コード
// Aは問題ない
// Bはコンパイルできるけど出力が異なる。
// Cはコンパイルできるけど出力が異なる
// Dについて、nameプロパティは文字列のみでnullは代入できない
// Dを修正してみる
class Cat(var name: String? = "") {
fun Meow() {
println("Meow!")
}
}
// おまけ
class CatOther(var name: String = "") {
fun Meow() {
println("Meow!")
}
fun P() {
print("${name}: ")
Meow()
}
}
fun main() {
var myCats = arrayOf(
Cat("Misty"),
Cat(null),
Cat("Socks")
)
for (cat in myCats) {
if (cat.name != null) {
print("${cat.name}: ")
cat.Meow()
}
}
var myCatsOther = arrayOf(
CatOther("Misty"),
null,
CatOther("Socks")
)
for (cat in myCatsOther) {
cat?.P()
}
}入出力結果
Misty: Meow! Socks: Meow! Misty: Meow! Socks: Meow! Process finished with exit code 0
0 コメント:
コメントを投稿