ä¹ ã ã«Kotlinå ¬å¼ããã°ã®æ´æ°ãããã¾ããï¼
How do you traverse a map? | Project Kotlin
ã¾ããªãçºè¡¨ããããã¤ã«ã¹ãã¼ã³3 (M3) ã§å°å ¥ãããæ°æ©è½ã®ä¸é¨ãç´¹ä»ããã¦ãã¾ãããã®æ°æ©è½ã¯å¤éå®£è¨ (Multi-declarations)ã¨ãã¼ã¿ã¯ã©ã¹ã§ãããã®ä¸¡æ©è½ã¯ç¾è¡ã®ã¿ãã«ã«åã£ã¦ä»£ããæ©è½ã§ãã
å¤é宣è¨
å¤é宣è¨ããã使ããã¨ã«ãªãã§ãããã·ã¼ã³ã¯ããã¼ããªã¥ã¼ãã¢ã®ã¤ãã¬ã¼ãã§ãã
for((key, value) in map) { println("$key : $value") }
Mapåã®å¤æ°mapã«å¯¾ãã¦ç¹°ãè¿ããè¦ç´ ãåãåºãã¦ãã¾ããåãåºãããè¦ç´ ã¯ãã¼ã¨ããªã¥ã¼ã®2ã¤ã§ãããããããåãåãå¤æ°ã2ã¤ç¨æããã¦ãã¾ããå¤æ°keyã¨å¤æ°valueã§ãã
ãããKotlinã®å¤é宣è¨ã§ãã
ãã®å¤é宣è¨ãå¯è½ã«ãã¦ããä»çµã¿ã¯ãè¤æ°ã®å¤ãè¿ãæ©è½ããã£ãåã§ããå
ã®ä¾ã§ã¯Mapåã§ããã
å¤é宣è¨æ©è½ã«ããè¤æ°ã®å¤ãè¿ãã«ã¯ãé¢æ° component*()ãæä¾ããå¿
è¦ãããã¾ãã*ã®é¨åã¯ä»»æã®æ´æ°ã§ãï¼ä¸éã¯ããã®ããªï¼ï¼ã
ä¾ãã°æ¬¡ã®ãããªã¯ã©ã¹ã¯ãå¤é宣è¨ã«å¯¾å¿ããåã¨è¨ãã¾ãã
class Person(val name : String, val age : Int) { fun component1() = name fun component2() = age }
é¢æ° component*()ã¯ãæ¡å¼µé¢æ°ã¨ãã¦å®ç¾©ãã¦ãåé¡ããã¾ããã
ãã¼ã¿ã¯ã©ã¹
OOPãè¡ãä¸ã§ãããããã£ã®ã¿ãæã¡ãç¹å¥ãªæä½ï¼ã¡ã½ããçï¼ããªãã¯ã©ã¹ããã°ãã°å¿
è¦ã«ãªãã¾ãããã®ãããªå ´åJavaã§ã¯ãéå±ãªã³ã¼ããä½åè¡ãæ¸ãå¿
è¦ãããã¾ããï¼ãã£ã¼ã«ããã¢ã¯ã»ãµã¡ã½ããçï¼ã
Kotlinã§ã¯ç°¡åã«ãã®ãããªã¯ã©ã¹ãè¨è¿°ã§ãã¾ãã次ã®ã¯ã©ã¹ã¯nameã¨ageã¨ããããããã£ã¨ã³ã³ã¹ãã©ã¯ã¿ã®ã¿ãæã£ãã¯ã©ã¹å®ç¾©ã§ãã
class Person(val nage : String, val age : Int)
ç°¡åã§ããã
ããã¦ãããã«ãã¼ã¿ã¯ã©ã¹ãç°¡åã«å®ç¾©ã§ããdataã¢ããã¼ã·ã§ã³ã追å ããã¾ããããã®dataã¢ããã¼ã·ã§ã³ãä»ããã¯ã©ã¹ã«ã¯ãèªåçã«é¢æ° component*()ãçæããã¾ããã³ã³ã¹ãã©ã¯ã¿ã§å®£è¨ããããããã£ã®é ã« component*()ãçæããã¾ãã
data class Person(val name : String, val age : Int) fun main(args : Array<String>) { val persons = LinkedList<Person>() persons.add(Person("hoge", 20)) persons.add(Person("fuga", 30)) persons.add(Person("piyo", 40)) for ((name, age) in persons) { println("$name is $age years old.") } }
ãã®ã³ã¼ããå®è¡ããã¨ã次ã®ããã«åºåããã¾ãã
hoge is 20 years old. fuga is 30 years old. piyo is 40 years old.
ç¾æç¹ã§ã¯ã¾ã å®è£
ããã¦ãã¾ããããä»å¾ã¯component*()ã®ä»ã«toString()ãequals()çãdataã¢ããã¼ã·ã§ã³ã«ããèªåçæããããããã§ãã
M3ããã¿ãã«æ©è½ã¯åé¤ããã¾ãããé¢æ°ããè¤æ°ã®å¤ãè¿ãããã¨ãã«ã¯ãã¼ã¿ã¯ã©ã¹ã使ç¨ãããã¨ã«ãªãã¾ãã