Any.toString()
すべてのクラスのスーパークラスである Any
には次のようにメンバ関数 toString()
が定義されている。
open fun toString(): String
これが適切にオーバーライドされたクラスであれば、
そのインスタンスに対してこの関数を呼び出すことで
適切な文字列を得ることができる。
println(
listOf("I", "love", "Kotlin", ".")
.toString()
) // > [I, love, Kotlin, .]
Any?.toString()
null
はオブジェクトではないのでメンバ関数を持たない。
しかし null
に対してメンバ関数 toString()
を呼び出しても
コンパイルエラーにならないし、
実行時には "null"
という文字列が返る。
println(
null.toString()
) // > null
これは言語仕様でそうなっているという訳ではない。
標準ライブラリーで次の拡張関数が定義されているからこのように動作するのである。
fun Any?.toString(): String
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"
/以上