Help us understand the problem. What is going on with this article?

実際にあった scala.App の怖い間違い

More than 1 year has passed since last update.

今日見たかもしれない話。

Scala を学び始めると比較的最初の方に出て来るであろう scala.App ってありますね。 継承すると def main() を定義しなくて良いやつ。

object Main extends App {
  println("Hello World")
}

main() 関数が生えるので、次のように実行できます。

Main.main(Array()) // Hello World が印字される

これで App の使い方は覚えました。

さて、次のように同じような object が2つあったとします(Main1Main2)。

object Main1 extends App {
  def printClassName(): Unit = println("Main1")

  println("Start")
  printClassName()
  println("Finish")
}

object Main2 extends App {
  def printClassName(): Unit = println("Main2")

  println("Start")
  printClassName()
  println("Finish")
}

似たような処理が複数箇所にあるのは良くないので、共通の親クラス(SuperMain)にまとめます。

trait SuperMain extends App {
  def printClassName(): Unit

  println("Start")
  printClassName()
  println("Finish")
}
object Main1 extends SuperMain {
  def printClassName(): Unit = println("Main1")
}
object Main2 extends SuperMain {
  def printClassName(): Unit = println("Main2")
}

… さて、何を間違ったでしょうか?

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした