The first glance at Scala

 这也是从SolidMCP@Baidu搬家而来: The first glance at Scala

 

Piaoger当年学Python,花了一晚,对照一简明教程了解基本语法,为防止忘记,整理一个The first glance at Python,忘记怎么写了,可以随时参考。之于Scala,自然也就有了Thefirst glance at Scala。

大概的去年的这个时候开始接触SaaS, 一年之间,JVM、Groovy、Java和Scala之类的字眼渐入眼帘。今夜不能寐,终于下决心宠幸一把Scala,假以登堂而入JVM之室。

 

>> 环境配置:

在学习Python时选择Wing IDE尝到了甜头,借助Wing IDE强大的Debug功能,我可以迅速上手。至于上手之后,IDE反倒是那么重要了。

为了学习Scala,我选择了IntelliJ IDEA。

 

>> Scala Interpreter

在Console中敲入scalar,进入。。。。



>> 把玩Scala Interpreter



比较特别的是,Scala会产生一个默认的对象,我们直接使用这个对象。

 

在Interpreter中,我们还可以简单定义变量和方法,有图为证:


>> 初试Scala Script

 无它,唯将代码写在某文本文件中,然后在Console中以scala FileName运行之,即可!

 

 >>  While循环

var i = 0
while(i <= 100){
    i += 1
}
println(i)

 

 >> foreach 与 for

PrintArgs.scala

args.foreach(arg => println(arg))
args.foreach((arg: String) => println(arg))
args.foreach(println)  // Only one argument

for(arg <- args)
  println(arg)

-----------------------------------------------------------------------------------------

C:\Users\Piaoger>scala c:\scala\printargs.scala arg1 arg2 arg3 arg4
arg1
arg2
arg3
arg4
arg1
arg2
arg3
arg4
arg1
arg2
arg3
arg4
arg1
arg2
arg3
arg4

 -----------------------------------------------------------------------------------------

>> Data Structures(Array, List, Set and Map)

// Array
val greetStrings = new Array[String](3)
greetStrings(0) = "Hello"
greetStrings(1) = ", "
greetStrings(2) = "world!\n"
for (i <- 0 to 2)
  print(greetStrings(i))
  
// List
val oneTwo = List(1, 2)
val threeFour = List(3, 4)
val oneTwoThreeFour = oneTwo ::: threeFour
println(oneTwo + " and " + threeFour + " were not mutated.")
println("Thus, " + oneTwoThreeFour + " is a new List.")

// Set
import scala.collection.mutable.HashSet
val jetSet = new HashSet[String]
jetSet += "Lear"
jetSet += ("Boeing", "Airbus")
println(jetSet.contains("Cessna"))

// Map
import scala.collection.mutable.HashMap
val treasureMap = new HashMap[Int, String]
treasureMap += 1 -> "Go to island."
treasureMap += 2 -> "Find big X on ground."
treasureMap += 3 -> "Dig."
println(treasureMap(2))
al romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V")
println(romanNumeral(4))

-----------------------------------------------------------------------------------------

C:\Users\Piaoger>scala c:\scala\datastructure.scala
Hello, world!
List(1, 2) and List(3, 4) were not mutated.
Thus, List(1, 2, 3, 4) is a new List.
false
Find big X on ground.
IV
-----------------------------------------------------------------------------------------

 

 >>  Scala中的类与方法,以及独特的Constructor定义方式

// Common Class, Memer and Method
var strValue = new String("sdf")
println(strValue)

class MyClass{
val str="Hello "
def SayHelloTo(name: String)= println(str + name)
}
var newclass = new MyClass
newclass.SayHelloTo("Mike")

// Special constructor
class FancyGreeter(greeting: String) {
  def greet() = println(greeting)
}
val g = new FancyGreeter("Salutations, world")
g.greet()

// Special constructor with memeber validation
class CarefulGreeter(greeting: String) {
  if (greeting == null) {
    println("NULL is not allowed")
  }
  def greet() = println(greeting)
}

var validator = new CarefulGreeter(null)

// Define constructor in this method.
class RepeatGreeter(greeting: String, count: Int) {
  def this(greeting: String) = this(greeting, 1)
  def greet() = {
    for (i <- 1 to count)
      println(greeting)
  }
}

val g1 = new RepeatGreeter("Hello, world", 3)
g1.greet()
val g2 = new RepeatGreeter("Hi there!!!!!!!!!!")
g2.greet()

 

需要注意的是Scala中没有静态成员,需要使用Singleton Object来实现。

 

>> Scala Annotations

在Python中,有一些Annotation(Decoration??)用以修饰某些方法和属性,入用staticmethod就可以表示某个方法是static方法。

在Scala中有一些Annotation,这里只关注与class定义相关的BeanProperty.


BeanProperty

When attached to a field, this annotation adds a setter and a getter method following the Java Bean convention. For example:

@BeanProperty
varstatus = ""

adds the following methods to the class:

def setStatus(s: String) { this.status = s }
def getStatus: String = this.status

For fields of type Boolean, if you need a getter named isStatus, use the scala.reflect.BooleanBeanProperty annotation instead.

 

>> Scala中的Traits

Traits是Scala中实现Mixin的方法,可以实现

trait Similarity {
def isSimilar(x: Any): Boolean
def isNotSimilar(x: Any): Boolean = !isSimilar(x)
}

 

class Point(xc: Int, yc: Int) extends Similarity {
var x: Int = xc
var y: Int = yc
def isSimilar(obj: Any) =
obj.isInstanceOf[Point] &&
obj.asInstanceOf[Point].x == x
}

 

val p1 = new Point(2, 3)
val p2 = new Point(2, 4)
val p3 = new Point(3, 3)
println(p1.isNotSimilar(p2))
println(p1.isNotSimilar(p3))
println(p1.isNotSimilar(2))


---------------------------------------------------------------------------------
false
true
true
----------------------------------------------------------------------------------

 

>> Scala 与XML

如果说Javascript对JSON是原生支持的话,那么Scala对于XML也可以算作如胶似漆。

在Scala代码中可以嵌套XML:

object XMLTest1 extends Application {
val page =
<html>
<head>
<title>Hello XHTML world</title>
</head>
<body>
<h1>Hello world</h1>
<p><a href="scala-lang.org">Scala</a> talks XHTML</p>
</body>
</html>;
println(page.toString())
}

 

在XML中可以混杂Scala方法

object XMLTest2 extends Application {
import scala.xml._
val df = java.text.DateFormat.getDateInstance()
val dateString = df.format(new java.util.Date())
def theDate(name: String) =
<dateMsg addressedTo={ name }>
Hello, { name }! Today is { dateString }
</dateMsg>;
println(theDate("John Doe").toString())
}

正是我中有你,你中有我。人在人上,肉在肉中。

 

 

# References

http://www.artima.com/scalazine/articles/steps.html

https://wiki.scala-lang.org/display/SW/Tools+and+Libraries

 

posted on 2012-05-06 09:35  飘行天下  阅读(347)  评论(0编辑  收藏  举报

导航