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のDelegateサンプルコードがエラーになったので直した

Posted at

こちらの「サンプルコード7」がビルドエラーになったので
エラー解消後のコードを載せておく
interfaceが足りていなかった。
Robotの引数もinterface
https://jp-seemore.com/app/14661/#toc2


class Robot(soundBehavior: SoundBehavior, lightBehavior: LightBehavior) : SoundBehavior by soundBehavior,
    LightBehavior by lightBehavior

interface SoundBehavior {
    fun makeSound()
}

interface LightBehavior {
    fun illuminate()
}

class Sound : SoundBehavior {
    override fun makeSound() {
        println("音を鳴らす!")
    }
}

class Light : LightBehavior {
    override fun illuminate() {
        println("光を放つ!")
    }
}

val robot = Robot(Sound(), Light())
robot.makeSound() // SoundBehaviorのmakeSound()を呼び出す
robot.illuminate() // LightBehaviorのilluminate()を呼び出す

こういう風に引数をinterfaceにしていないと意味内容に思いますよね。
例えば別のLigthがあった場合にそれを引数にとれないのは拡張性がなさそう。

class Robot(soundBehavior: SoundBehavior, lightBehavior: LightBehavior) : SoundBehavior by soundBehavior,
    LightBehavior by lightBehavior
    
class DownLight : LightBehavior {
    override fun illuminate() {
        println("下向きに光を放つ!")
    }
}

val robot = Robot(Sound(), DownLight())
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?