0
1

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.

Kotlin入門:拡張関数

Posted at

拡張関数

継承を使わずに既存のクラスにメソッドを追加するための仕組みです。
本来のクラスに元からあったかのように追加できます。

構文:

fun clazz.name(param:type):rtype{}

clazz:拡張対象のクラス
name:メソッド名
param:引数名
type:引数の型
rtype:戻り値の型

入力例:

fun String.repeat(number:Int):String{
    var builder = StringBuilder()
    //指定された回数だけ文字列を連結
    for(i in 1..number){
        //ここでのthisはclazzのこと
        builder.append(this)
    }
    return builder.toString()
}
fun main() {
    val name = "山田"
    println(name.repeat(4))
}

実行結果は以下の通りです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?