社å scalaåå¼·ä¼#3ã¾ã¨ã
ä»ã®ä¼ç¤¾å
ã§Scalaåå¼·ä¼ãéå¬ããã¦ãã®ã§ã¾ã¨ãã
twitterããå
¬éããã¦ããScala Schoolã使ã£ã¦ãã¾ãã
http://twitter.github.com/scala_school/
ä»åã¯Collectionsã®ååã
http://twitter.github.com/scala_school/collections.html
以ä¸ã®ã³ã¼ãã®å¼ç¨ã¯ã»ã¨ãã©Scala Schoolã®ãã®ã§ãã
ããã¯ãã³ãã¼
#1 @satococoaãã
http://www.223soft.net/56
#2 @netwillnetãã
http://d.hatena.ne.jp/willnet/
Lists
ãµã¤ã¼ã«é å
val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4)
Sets
éè¤ããªãé åãJavaã®Listã¨Setã®é¢ä¿ã¨åæ§
scala> Set(1, 1, 2) res0: scala.collection.immutable.Set[Int] = Set(1, 2)
Tuple
ããã¯ããã¾ãè¦ãªãæ¦å¿µã§ããã
ä½ãé
åã¨éãããï¼ã¨æã£ãããå®éæ©è½ä¸ã¯ã»ã¼å¤ãããªãã
è²ã
ããã£ã¦èª¿ã¹ãçµæãé
åã¯ãè¤æ°ã®åã種é¡ã®ã¢ããæ ¼ç´ãã«å¯¾ããã¿ãã«ã¯ãè¤æ°ã®å¤ã§è¡¨ç¾ãããä¸ã¤ã®ãã¼ã¿ãæ ¼ç´ãããã£ã½ãã
ããã¯ã©ã¹ã§ã§ãããããï¼ã¨ãæãã¾ãããJavaã§ãã¼ã¿ã ãå
¥ããã¡ãã£ã¨ããã¯ã©ã¹ãä½ãã·ãã¥ã¨ã¼ã·ã§ã³ãæ³å®ãã¦ãããã§ãã
ä»ã§èª¿ã¹ãçµæãã¿ãã«ã®2å¤éå®ã¯Pairã3å¤éå®ã¯Tripleã¨ããå¥åããããããã
scala> val hostPort = ("localhost", 80) hostPort: (String, Int) = (localhost, 80)
ã¾ãããã£ã¦ãããã®ä¾ãè¦ãã°ä¸ç®çç¶ã
scala> hostPort._1 res0: String = localhost
scala> hostPort._2 res1: Int = 80
ã¢ã¯ã»ã¹ããã«ã¯ã_nãã¨ããã¢ã¯ã»ãµã使ç¨ã
hostPort match { case ("localhost", port) => ... case (host, port) => ... }
ãã¿ã¼ã³ãããã«ã使ããã便å©ããã
scala> 1 -> 2 res0: (Int, Int) = (1,2)
ããããæ¸ãæ¹ããããè¦ç´ ä¸åã®Mapã£ã½ãã
Maps
Javaã®MapãRubyã§ã¯hashã
Map(1 -> 2) Map("foo" -> "bar")
=>ã¯Functionã«åããã¦ãã®ã§Cè¨èªã§ããªãã¿ã¢ãã¼æ¼ç®åã使ããããã
Map(1 -> Map("foo" -> "bar")) Map("timesTwo" -> timesTwo(_))
ãããã®ä¸ã«ããããã¢ãªã
å¾è
ã¯ã©ããã£ã¦ãåããªãã£ãã®ã§
Map("timesTwo" -> timesTwo _ )
ã®èª¤è¨ãããªããï¼ã¨ããçµè«ã§ããã
Functionã®é¨åé©ç¨ãå
¥ããã¼ã¨ãããã¨ãã¾ãè¦ã¯ä½ã§ãå
¥ãã¨ã
ã¡ãªã¿ã«
val m = Map("key" -> "value" ) m.get("key")
ããçµæã¯valueã§ã¯ããã¾ãããå¾è¿°ã®Optionã§ãã
m.get("key").get
ã§"value"ãåå¾ã§ãã¾ãã
Option
ã§ãOptionãOptionã¯ãããªtraitã®ãããªã¢ãâ¦ãããã
trait Option[T] { def isDefined: Boolean def get: T def getOrElse(t: T): T }
scala> val numbers = Map(1 -> "one", 2 -> "two") numbers: scala.collection.immutable.Map[Int,String] = Map((1,one), (2,two))
scala> numbers.get(2) res0: Option[java.lang.String] = Some(two)
å¤ãããã¨ãã¯Some
scala> numbers.get(3) res1: Option[java.lang.String] = None
å¤ãç¡ãã¨ãã¯None
ãè¿ãã
Some[T]ã¨Noneã¯Optionã®ãµãã¯ã©ã¹ã
val result = if (res1.isDefined()) { res1.get * 2 } else { 0 }
ãããªã¨ãã
scala> numbers.get(3).getOrElse("default") res6: java.lang.String = default
ãããªã¨ããã¬ãã½ãå¿é ããã«æ¸ãããï¼
ã¾ã¨ã
ç§ã¯Javaãä¸çªé·ãã®ã§ããããJavaã§ããã©ããã¼ã¨ãããç°¡åã«ã§ããããã«ãã¦ãããªãã£ã¦ã®ãä»åã®å°è±¡ã§ããã
Cã»ã©ãããªãã«ãã¦ãJavaã®ã¬ãã½ãã§ãã¯ã¯ããã©ããããã2å¤ã®ã»ãããå
¥ããããã«commonsã©ã¤ãã©ãªã®Pairã¯ã©ã¹ä½¿ã£ãããã¦ãã®ã§ã
ã¨ã¯ãããOptionãããã¯ã¬ãã½ãã§ãã¯ã®ããã ããããªãã¦ãå¾åã®mapã¨ãfilterã¨ãã®é¢æ°åã£ã½ãæ©è½ãç°¡æ½ã«æ¸ãããã®æ©è½ã§ããããã ã¨æãã¾ãã
Scala Schoolã1ãã¼ã¸ç®ããã«ãªã¼åã¨ãé¨åé©ç¨ã¨ãããªãé£è§£ã§ããããä»åã¯å®ç¨çã§ããããããã£ãã¨æãã