1
0

More than 1 year has passed since last update.

【Kotlin】toString() 関数

Posted at

Any.toString()

すべてのクラスのスーパークラスである Any には次のようにメンバ関数 toString() が定義されている。

open fun toString(): String

Any.toString() の API ドキュメント

これが適切にオーバーライドされたクラスであれば、
そのインスタンスに対してこの関数を呼び出すことで
適切な文字列を得ることができる。

println(
    listOf("I", "love", "Kotlin", ".")
        .toString()
) // > [I, love, Kotlin, .]

Any?.toString()

null はオブジェクトではないのでメンバ関数を持たない。

しかし null に対してメンバ関数 toString() を呼び出しても
コンパイルエラーにならないし、
実行時には "null" という文字列が返る。

println(
    null.toString()
) // > null

これは言語仕様でそうなっているという訳ではない。

標準ライブラリーで次の拡張関数が定義されているからこのように動作するのである。

fun Any?.toString(): String

Any?.toString() の API ドキュメント

null に対して文字列 "null" を返すことについても API ドキュメントに次のように明記されている。

Can be called with a null receiver, in which case it returns the string "null".

なお実装は、先述の API ドキュメントからリンクされているが、次のようにシンプルなものである。

public inline fun Any?.toString() = this?.toString() ?: "null"

/以上

1
0
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
1
0