0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinでメソッドの挙動を変更する方法

Posted at

kotlinでメソッドの挙動を変更したい時、overrideで設定することで変更できる。

そのクラスにだけ適用したい場合(基本)

方法:toString() を override する

class User(val name: String) {

    override fun toString(): String {
        return "$name Ace"
    }
}
val user = User("Tom")
println(user.toString()) // Tom Ace

プロジェクト全体で統一したい場合

上記の適応範囲はこのクラスのみだが、プロジェクト全体に適応する場合は共通クラスを作成して使いまわせるようにする。

open class BaseModel {

    protected open fun baseToString(): String {
        return super.toString() + " Ace"
    }

    override fun toString(): String = baseToString()
}
class User(val name: String) : BaseModel() {
    override fun baseToString(): String {
        return "$name Ace"
    }
}
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?