Kotinã®ãã¤ã«ã¹ãã¼ã³5.3ãçºè¡¨ããã¾ããã
Kotlin M5.3: IntelliJ IDEA 13, Delegated Properties and more | Project Kotlin
IntelliJ IDEA 13ã¸ã®å¯¾å¿ã¨ãéããªãAndroid Studioã«ã対å¿ãããã¨ãã³ã³ãã¤ã©ã®æ§è½æ¹åã¨IDEã®æ©è½å¢å¼·ã«ã¤ãã¦è¨åããã¦ãã¾ãããã®ä»ã«Kotlinè¨èªã®æ°ããæ©è½ã¨ãã®ã·ã³ã¿ãã¯ã¹ãçºè¡¨ããã¦ãã¾ããç¹ã«é¢ç½ãã¨æã£ã2ã¤ã®æ©è½ã«ã¤ãã¦ç´¹ä»ãã¾ãã
Delegated Property
ããããã£ãé 延åæåããããå¤ã®å¤æ´ã®ç£è¦ããããå ´é¢ãããã¾ãããï¼ãããªã¨ãã¯ã³ã¼ããããããæ¸ãã¦ãã¾ããããDelegated Propertyã¯ãã®ãããªä»æããç¨æããããã®æ©è½ãè¨èªã¬ãã«ã§æä¾ãã¾ãã 次ã®ãµã³ãã«ã³ã¼ããè¦ã¦ãã ãã*1ã
class Example { var p: String by Delegate() } class Delegate() { fun get(thisRef: Any?, prop: PropertyMetadata): String { return "${thisRef}ã®${prop.name}ãåç §ããã¾ããã" } fun set(thisRef: Any?, prop: PropertyMetadata, value: String) { println("${thisRef}ã®${prop.name}ã«${value}ãå²ãå½ã¦ããã¾ããã") } }
ããããã£ã®åã®å¾ã«by
ãç½®ããç¶ãã¦å§è²å
ã®ãªãã¸ã§ã¯ããæå®ãã¾ãããã®ããããã£ã¸ã®ã¢ã¯ã»ã¹ã«å¯¾ãã¦å§è²å
ã®ãªãã¸ã§ã¯ããåãã¦ãããã¨ããããã§ããããããã£ã«å¯¾ããgetã¨setã¯ãããããå§è²å
ãªãã¸ã§ã¯ãã®get
ã¡ã½ãããset
ã¡ã½ãããå¼ã³åºããã¾ããå§è²å
ãªãã¸ã§ã¯ãï¼ããã§ã¯Delegate
ãªãã¸ã§ã¯ãï¼ã¯ä½ãç¹å¥ãªãã¬ã¤ããå®è£
ãã¦ã¯ããªãç¹ã«æ³¨æãã¦ãã ãã*2ãã¡ã½ããã®æç¡ã§å§è²å
ãªãã¸ã§ã¯ãã¨ãã¦å¦¥å½ãã©ãããã³ã³ãã¤ã©ã¯å¤æãã¾ãã
val e = Example() println(e.p) e.p = "NEW"
ãã®ã³ã¼ãã®å®è¡çµæã¯æ¬¡ã®ããã«ãªãã¾ãã
Example@6c22c95bã®pãåç §ããã¾ããã Example@6c22c95bã®pã«NEWãå²ãå½ã¦ããã¾ããã
ãã®æ©è½ã使ãã°ãããããã£ã®é
延åæåãå¤æ´ç£è¦ãç°¡åã«ã§ããããã«ãªãã¾ããããããããèªåã§å®è£
ããå¿
è¦ã¯ããã¾ãããKotlinã®æ¨æºã©ã¤ãã©ãªkotlin.properties
ããã±ã¼ã¸å
ã«ï¼ç¹ã«Delegates
ã·ã³ã°ã«ãã³ãªãã¸ã§ã¯ãå
ã«ï¼å§è²å
ãªãã¸ã§ã¯ãã®ãã¡ã¯ããªé¢æ°ãæã£ã¦ãã¾ããä¾ãã°é
延åæåã®ããã®kotlin.properties.Delegates.lazy
é¢æ°ã¯æ¬¡ã®ããã«ä½¿ç¨ãã¾ãã
import kotlin.properties.Delegates class Example { val p: String by Delegates.lazy { println("åæå") "hoge" } } fun main(args: Array<String>) { val e = Example() println("-----") println(e.p) println(e.p) }
ãã®ã³ã¼ãã®å®è¡çµæã¯æ¬¡ã®ããã«ãªããåæåã®é 延ãä¸æããã£ã¦ãããã¨ããããã¾ãã
----- åæå hoge hoge
Callable Reference
Kotlinã«ã¯é«éé¢æ°ã®ä»çµã¿ããããã¤ã¾ãé¢æ°ããã¡ã¼ã¹ãã¯ã©ã¹ã¨ãã¦æ±ããã¨ãã§ãã¾ãããã ãï¼ãã¡ã¼ã¹ãã¯ã©ã¹ãªã®ã¯é¢æ°ãªãã©ã«è¡¨è¨ã§çæããé¢æ°ã®ã¿ã§ãfun
ãã¼ã¯ã¼ããä¼´ã£ã¦å®ç¾©ãããé¢æ°ã¯ãã¡ã¼ã¹ãã¯ã©ã¹ã§ã¯ããã¾ããã§ããã次ã®ã³ã¼ãã¯æå¾
éãã«åãã¾ãã
fun main(args: Array<String>) { val next ={(n: Int) -> n + 1} println(listOf(1, 2, 3).map(next)) // [2, 3, 4] }
次ã®ããã«fun
宣è¨ãããé¢æ°ã§ã¯ä¸æãããã¾ããã
fun next(n: Int) = n + 1 fun main(args: Array<String>) { println(listOf(1, 2, 3).map(next)) // ããã§ã³ã³ãã¤ã«ã¨ã©ã¼ }
ãã®åé¡ãæ°æ©è½Callable Referenceã¯è§£æ±ºãã¦ããã¾ããfun
宣è¨ãããé¢æ°ã®åç
§ã渡ãã«ã¯ã::
ï¼ã³ãã³2åï¼ãé¢æ°åã®åã«ä»ããã ãã§ãã次ã®ã³ã¼ãã¯fun
宣è¨ãããé¢æ°ã®åç
§ãé¢æ°ã®å¼æ°ã¨ãã¦æ¸¡ãã¦æå¾
éãã«è¨ç®ãè¡ãã¾ãã
fun next(n: Int) = n + 1 fun main(args: Array<String>) { println(listOf(1, 2, 3).map(::next)) // [2, 3, 4] }
ããã¯é常ã«ä¾¿å©ã§ãããªãä»ã¾ã§ãªãã£ãã®ãä¸æè°ãªãããã§ãããã®æ©è½ã¯ã¾ã ã¾ã çºå±éä¸ã§ãã®ã§ã注æãï¼next
ãmain
ã®ãã¼ã«ã«é¢æ°ã«ããã¨å®è¡æã¨ã©ã¼ãèµ·ããã¾ããï¼ã
第1åããããKotlinåå¼·ä¼
ã¤ãã«ï¼Kotlinã®åå¼·ä¼ãéå¬ãããã¨ã¨ãªãã¾ããï¼ ãã²å¥®ã£ã¦ãåå ãã ããï¼ï¼ ã¹ãã¼ã«ã¼åéä¸ã§ãã