5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala で printf

Posted at

主に C++ を使ってた人が Scala を学ぶシリーズ。
コンソール出力関数の使い方。

print.scala
class Main {

	// 出力
	print("Hello, World!\n")

	// 出力して改行
	println("Hello, World!")

	// フォーマットして出力
	printf("Hello, %s!\n", "World")
}
コンソール入力
> scala
> :load print.scala
> new Main
コンソール出力
Hello, World!
Hello, World!
Hello, World!

print 関数は内部で toString 関数を呼び出すので、toString 関数が定義されていれば文字列以外の型も渡せます。
Scala バージョン 2.11.6 で動作確認。

補足

Scala では class の下のレベルに処理を書くと、それがコンストラクタになります。
上に書いた print.scala は cpp で書くとこんな感じのようです。

# include <cstdio>

class Main {

public:
  Main() {
    printf("Hello, %s!\n", "World");
  }
}

コンストラクタに引数を渡したい時は class 宣言の後ろに引数を書きます。

print.scala
class Main2[Type](str : Type) {
  println(str)
}
コンソール入力
> scala
> :load print.scala
> new Main2("Hello, World!")
コンソール出力
Hello, World!

[Type] というのはテンプレートです。
cpp で書くとこんな感じしょうか。

template <typename Type>
class Main2 {

public:
  Main2(const Type& str) {
    printf("%s\n", str.toString());
  }
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?