[Scala][從C# 到 Scala]Scala:映射;C#:字典

  • 713
  • 0
  • 2014-07-09

[Scala][從C# 到 Scala]Scala:映射;C#:字典

Scala:映射;C#:字典

 

Scala:

   1:  
   2: var scores=scala.collection.mutable.Map[String,Int]("Alice"-> 10,"Bob"-> 3,"Cindy"-> 8)
   3: //val scores=Map("Alice"-> 10,"Bob"-> 3,"Cindy"-> 8)
   4: println(scores ("Alice"))
   5: val result=if(scores.contains("God"))scores("God") else false
   6: //result=scores.getOrElse("God",false)
   7: println(result)
   8:  
   9: //賦值 也可更新 語法一樣
  10: //scores("God")=99
  11: scores+=("God"->99)
  12: //將插入在God以後,觀看結果Mary位置,即可發現
  13: scores+=("God"->77,"Mary"->123)
  14: println(scores("God"))
  15: println(scores)
  16: //刪除
  17: //scores=scores-"God"-"Mary"
  18: scores-=("God")
  19: scores-=("God")
  20: scores-=("God","Mary")
  21: println(scores)

 

Result:

image

 

 

 

C#:

   1:  
   2: Dictionary<string,int>scores=new 
   3: Dictionary<string,int>();
   4: scores.Add("Alice",10);
   5: scores.Add("Bob",3);
   6: scores.Add("Cindy", 8);
   7: Console.WriteLine(scores["Alice"]);
   8: object 
   9: result;
  10: result = scores.ContainsKey("God") ? scores["God"] as object: false 
  11: as object;
  12: Console.WriteLine(result);
  13: //賦值
  14: scores.Add("God",99);
  15: scores.Add("Mary", 123);
  16: Console.WriteLine(scores["God"]);
  17: scores.ToList().ForEach(x=>
  18:     {
  19:          Console.Write("{0}->{1},", x.Key, 
  20:         x.Value.ToString());
  21:     });
  22: Console.WriteLine();
  23: //刪除
  24: scores.Remove("God");
  25: scores.Remove("Mary");
  26: scores.ToList().ForEach(x =>
  27:     { 
  28:             Console.Write("{0}->{1},", x.Key, 
  29:             x.Value.ToString());
  30:     });
  31: Console.WriteLine();
  32: Console.Read();

 

Result:

image

 

 

心得:

Scala除了提供好識別化的語法糖,還做了很多防呆的機制,有些防呆原本若不去處理,很容易程式就會崩潰,這些小防呆常常就被遺漏了,現在不用擔心那麼多,單純寫邏輯吧。

 

 

By-藍小伙