Kotlinã«ã¯Class Delegationã¨ããæ©è½ãããã¾ãã å ¬å¼ããã¥ã¡ã³ãã¯ãã¡ãã
ããã®ä½¿ãéã«ã¤ãã¦æ¸ãããã¨æãã¾ãã
ããããClass Delegationã£ã¦ï¼
Delegationãã¤ã¾ãå§è²ã®ä»çµã¿ã§ãã
ä¾ãã°ãããªæãã
// æ¨æ¶ãã人ã®ã¤ã³ã¿ãã§ã¼ã¹ trait Greeter { fun greet() } // Greeterã®å®è£ ã¯ã©ã¹(ã¨ããããªãã¸ã§ã¯ã) object JapaneseGreeter: Greeter { override fun greet() { println("ããã«ã¡ã¯") } } // ããã§Class Delegationã使ã£ã¦ãã class Person(greeter: Greeter): Greeter by greeter fun main(args: Array<String>) { val person = Person(JapaneseGreeter) // personã¯greet()ã¡ã½ãããå¼ã³åºãã person.greet() // => ããã«ã¡ã¯ // personã¯Greeterã®ãµãã¿ã¤ã val greeter: Greeter = person }
Person
ã¯ã©ã¹ã¯: Greeter
ã«ããGreeter
ãã¬ã¤ããå®è£
ãã¦ãã¾ããããPerson
ã«ã¯greet
ã¡ã½ããã®å®ç¾©ã¯ããã¾ããã: Greeter by greeter
ã¨æå®ãããã¨ã§ã³ã³ã¹ãã©ã¯ã¿ã§åãåãgreeter
ã«å¦çãå§è²ãããã®ã§ãã
ãªãã»ã©ãæ¸ãæ¹ã¯ããã£ãããããä½ã«å½¹ç«ã¤ã®ã§ããããã
ãç¶æ¿ããã³ã³ãã¸ã·ã§ã³ãé¸ã¶ã
Effective Java第2çã®é ç®16ã«ã¯ãç¶æ¿ããã³ã³ãã¸ã·ã§ã³ãé¸ã¶ãã¨ããæããæ²ãããã¦ãã¾ãã å ·è±¡ã¯ã©ã¹(å®è£ )ãç¶æ¿ãã¦ãããããå·®åããã°ã©ãã³ã°ã§æ¥½ãããèªæã«é§ããããã¨ã®ãã人ã¯å¤ãã¨æãã¾ãã ãããå®è£ ã®ç¶æ¿ã¯è½ã¨ãç©´ãããã¾ãã ç¶æ¿ã¯å®è£ ã®ããã§ã¯ãªããåã®ããã«è¡ãã¹ãã§ãã 詳細ã¯ãã®è¨äºãããããããã§ãã
ãã¦ãKotlinã®Class Delegationã®è©±ã«æ»ãã¾ãã
å
ã«ç¤ºããã³ã¼ãã§ãPerson
ã¯Greeter
ã®ãµãã¿ã¤ãã§ãã
Greeter
ã¯ã¤ã³ã¿ãã§ã¼ã¹ãªã®ã§å®è£
ã®ç¶æ¿ã§ã¯ãªãåã®ç¶æ¿ã§ãã
ããã¦Person
ã«ã¯å®è£
ã®è¨è¿°ã¯ããã¾ãããåä½ãã¾ãã
å®è£
ã¯ã³ã³ã¹ãã©ã¯ã¿ã§æ¸¡ãããgreeter
ã«å§ãããã¾ãã
è¨ããããã¨ã¯ãå®è£
ã§ã¯ãªãåã®ã¿ã®ç¶æ¿ãè¡ããå®è£
ã®ç¶æ¿ã«ä»ãç©ã®è½ã¨ãç©´ãåé¿ãã¤ã¤ãå·®åããã°ã©ãã³ã°ã®ãããªæ軽ããClass Delegationã¯å®ç¾ãã¦ããããã¨ãããã¨ã§ãã
å ·ä½ä¾
åãé¡æã使ãã¾ãã
æ¿å
¥ãããåæ°ãè¨æ¶ããSet
ãä½ãããã¨æãã¾ãã
ä¸è¨è¨äºã§ã¯HashSet
ãããªãã¡å
·è±¡ã¯ã©ã¹ãç¶æ¿ãããã¨ã§æå¾
éãã«åããªãã¯ã©ã¹ãä½ã£ã¦ãã¾ã£ã¦ãã¾ãã
ããã§ã¹ã¼ãã¯ã©ã¹ã®å®è£
ã«å½±é¿ãåããªãããã«ãã¤ã³ã¿ãã§ã¼ã¹ã®ãµãã¿ã¤ãã¨ãªãå
·è±¡ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã¸å§è²ãã(ä¸è¨è¨äºã§ã¯ã転éãã¨ããè¨èã使ããã¦ãã¾ãã)ãããªæ¹æ³ãæ¡ã£ã¦ãã¾ãããã£ã¼ã«ãã«å
·è±¡ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ãä¿æããã¤ã³ã¿ãã§ã¼ã¹ãæä¾ããæ½è±¡ã¡ã½ããããã¹ã¦å®è£
ãã¦ãç¬èªã®æ¯ãèããæããªãå ´åã«ã¯åã«å
·è±¡ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹ã¸ãã®ã¾ã¾å¦çãæµãããã¨ããæãã«ãªãã¾ãã
ãã®ãããããã¿ã¼ã³ãClass Delegationã使ãã¨ç°¡åã«è¨è¿°ã§ãã¾ããå®éã®ã³ã¼ãã¯ããã§ãã
class InstrumentedSet<E>(private val s: MutableSet<E>) : MutableSet<E> by s { var addCount: Int = 0 private set override fun add(e: E): Boolean { addCount++ return s.add(e) } override fun addAll(c: Collection<E>): Boolean { addCount += c.size() return s.addAll(c) } } fun main(args: Array<String>) { val instrumentedSet = InstrumentedSet(java.util.HashSet<String>()) instrumentedSet.add("hoge") instrumentedSet.add("fuga") instrumentedSet.addAll(listOf("a", "b", "c")) println(instrumentedSet.addCount) // => 5 // InstrumentedSetã§å®ç¾©ãã¦ããªãå®è£ ã¯å§è²å ã®å®è£ ã使ããã println(instrumentedSet.contains("hoge")) // => true }
InstrumentedSet
ããªã¼ãã©ã¤ããã¦ããã¡ã½ããã¯2ã¤ã ãã§ãã
ãã®ä»ã«ãSet
ãæä¾ããæ½è±¡ã¡ã½ããã¯ããããããã¾ãããå
·è±¡ã¯ã©ã¹ã®ã¤ã³ã¹ã¿ã³ã¹s
ã«å§è²ããã ããªãããããè¨è¿°ããå¿
è¦ã¯ããã¾ããã
ãã®ããã«ãåã®ç¶æ¿ããã¤ã¤ãå®è£ ã¯å¤é¨ããã¤ã³ã¸ã§ã¯ãããããããªãã¿ã¼ã³ã®ããã®æ©è½ãClass Delegationã§ãã