各个编程语言都有类似的地方,我们只要精通一门语言,就可以对比着学习,要不了多久就可以精通另一门语言,在网上看到Swift语言和Scala语言的对比,我们就来看看他们之间的一些相似之处。
在WWDC 14上,苹果公司发布了一门新的编程语言Swift。这里有一个Swift和Scala的源代码对比,使用的是苹果公司在iTunes商店出版的《Swift编程语言》一书中的例子。
我猜测这两者是相关的,从语法上讲,Swift是Scala的一种方言。Swift从Scala继承了苹果列出的大部分标志性特性:类型推断、闭包、元组、协议、扩展、泛型、读取-执行-打印-循环(Read-Eval-Print-Loop)等等。
尽管它们的语法相似,Swift的运行时环境与Scala的截然不同,这可能是新语言最有趣的地方。Scala编译到JVM,使用垃圾收集,它的对象模型透明地与Java集成。Swift编译为本机代码,使用自动引用计数,其对象模型透明地与Objective-C集成。因此,这两种语言之间的相似性并没有延伸到表面之下。
Den Shabalin 提供了另一个优秀的 逐点比较.
p.s. 不要把这段代码看得太严重!大部分都是死记硬背,简化了苹果给出的快速例子。我给出了一些更符合Scala习惯用法的翻译。如果您发现任何令人难以忍受的问题,请随时提交GitHub问题/拉请求。
基础
Hello World
SWIFT
println("Hello, world!")
SCALA
println("Hello, world!")
变量和常量
SWIFT
var myVariable = 42
myVariable = 50
let myConstant = 42
SCALA
var myVariable = 42
myVariable = 50
val myConstant = 42
显式类型
SWIFT
let explicitDouble: Double = 70
SCALA
val explicitDouble: Double = 70
强制类型转换
SWIFT
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
SCALA
val label = "The width is "
val width = 94
val widthLabel = label + width
字符串插值
SWIFT
let apples = 3
let oranges = 5
let fruitSummary = "I have \(apples + oranges) " +
"pieces of fruit."
SCALA
val apples = 3
val oranges = 5
val fruitSummary = s"I have ${apples + oranges} " +
" pieces of fruit."
半开区间运算符 (Range Operator)
SWIFT
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..count {
println("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
SCALA
val names = Array("Anna", "Alex", "Brian", "Jack")
val count = names.length
for (i <- 0 until count) {
println(s"Person ${i + 1} is called ${names(i)}")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
闭区间运算符(Inclusive Range Operator)
SWIFT
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
SCALA
for (index <- 1 to 5) {
println(s"$index times 5 is ${index * 5}")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
集合
数组/列表(Arrays)
SWIFT
var shoppingList = ["catfish", "water",
"tulips", "blue paint"]
shoppingList[1] = "bottle of water"
SCALA
var shoppingList = Array("catfish",
"water", "tulips", "blue paint")
shoppingList(1) = "bottle of water"
映射 Maps
SWIFT
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
SCALA
var occupations = scala.collection.mutable.Map(
"Malcolm" -> "Captain",
"Kaylee" -> "Mechanic"
)
occupations("Jayne") = "Public Relations"
Empty Collections 空集合
SWIFT
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
let emptyArrayNoType = []
SCALA
val emptyArray = Array[String]()
val emptyDictionary = Map[String, Float]()
val emptyArrayNoType = Array()
函数
Functions 函数
SWIFT
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
SCALA
def greet(name: String, day: String): String = {
return s"Hello $name, today is $day."
}
greet("Bob", "Tuesday")
Scala 惯用法 (IDIOMATIC SCALA)
def greet(name: String, day: String): String =
s"Hello $name, today is $day."
greet("Bob", "Tuesday")
元组返回 Tuple Return
SWIFT
func getGasPrices() -> (Double, Double, Double) {
return (3.59, 3.69, 3.79)
}
SCALA
def getGasPrices(): (Double, Double, Double) = {
return (3.59, 3.69, 3.79)
}
Scala 惯用法 IDIOMATIC SCALA
def getGasPrices = (3.59, 3.69, 3.79)
Variable Number Of Arguments 可变参数
SWIFT
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf(42, 597, 12)
SCALA
def sumOf(numbers: Int*): Int = {
var sum = 0
for (number <- numbers) {
sum += number
}
return sum
}
sumOf(42, 597, 12)
Scala 惯用法 IDIOMATIC SCALA
Array(42, 597, 12).sum
Function Type 函数类型
SWIFT
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
SCALA
def makeIncrementer(): Int => Int = {
def addOne(number: Int): Int = {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
Scala 惯用法 IDIOMATIC SCALA
def makeIncrementer: Int => Int =
(number: Int) => 1 + number
var increment = makeIncrementer
increment(7)
映射 Map
SWIFT
var numbers = [20, 19, 7, 12]
numbers.map({ number in 3 * number })
SCALA
var numbers = Array(20, 19, 7, 12)
numbers.map( number => 3 * number )
排序 Sort
SWIFT
sort([1, 5, 3, 12, 2]) { $0 > $1 }
SCALA
Array(1, 5, 3, 12, 2).sortWith(_ > _)
Named Arguments 命名参数
SWIFT
func area(#width: Int, #height: Int) -> Int {
return width * height
}
area(width: 10, height: 10)
SCALA
def area(width: Int, height: Int): Int = {
return width * height
}
area(width = 10, height = 10)
类
Declaration 声明
SWIFT
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
SCALA
class Shape {
var numberOfSides = 0
def simpleDescription(): String = {
return s"A shape with $numberOfSides sides."
}
}
Scala 惯用法 IDIOMATIC SCALA
class Shape (var numberOfSides: Int = 0) {
def simpleDescription =
s"A shape with $numberOfSides sides."
}
Usage 使用
SWIFT
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
SCALA
var shape = new Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
Subclass 子类
SWIFT
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length
\(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
Scala 惯用法 IDIOMATIC SCALA
class NamedShape(var name: String,
var numberOfSides: Int = 0) {
def simpleDescription =
s"A shape with $numberOfSides sides."
}
class Square(var sideLength: Double, name: String)
extends NamedShape(name, numberOfSides = 4) {
def area = sideLength * sideLength
override def simpleDescription =
s"A square with sides of length $sideLength."
}
val test = new Square(5.2, "my test square")
test.area
test.simpleDescription
类型检测 Checking Type
SWIFT
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
++movieCount
} else if item is Song {
++songCount
}
}
SCALA
var movieCount = 0
var songCount = 0
for (item <- library) {
if (item.isInstanceOf[Movie]) {
movieCount += 1
} else if (item.isInstanceOf[Song]) {
songCount += 1
}
}
Pattern Match 模式匹配
SWIFT
var movieCount = 0
var songCount = 0
for item in library {
switch item {
case let movie as Movie:
++movieCount
println("Movie: '\(movie.name)', dir. \(movie.director)")
case let song as Song:
++songCount
println("Song: '\(song.title)'")
}
}
SCALA
var movieCount = 0
var songCount = 0
for (item <- library) {
item match {
case movie: Movie =>
movieCount += 1
println(s"Movie: '${movie.name}', dir. ${movie.director}")
case song: Song =>
songCount += 1
println(s"Song: '${song.title}'")
}
}
向下类型转换 Downcasting
SWIFT
for object in someObjects {
let movie = object as Movie
println("Movie: '\(movie.name)', dir. \(movie.director)")
}
SCALA
for (obj <- someObjects) {
val movie = obj.asInstanceOf[Movie]
println(s"Movie: '${movie.name}', dir. ${movie.director}")
}
协议 Protocol
SWIFT
protocol Nameable {
func name() -> String
}
func f<T: Nameable>(x: T) {
println("Name is " + x.name())
}
SCALA
trait Nameable {
def name(): String
}
def f[T <: Nameable](x: T) = {
println("Name is " + x.name())
}
类型扩展 Extensions
SWIFT
extension Double {
var km: Double { return self * 1_000.0 }
var m: Double { return self }
var cm: Double { return self / 100.0 }
var mm: Double { return self / 1_000.0 }
var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
println("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
println("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
SCALA
object Extensions {
implicit class DoubleUnit(d: Double) {
def km: Double = { return d * 1000.0 }
def m: Double = { return d }
def cm: Double = { return d / 100.0 }
def mm: Double = { return d / 1000.0 }
def ft: Double = { return d / 3.28084 }
}
}
import Extensions.DoubleUnit
val oneInch = 25.4.mm
println(s"One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.ft
println(s"Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"
Scala惯用法 IDIOMATIC SCALA
object Extensions {
implicit class DoubleUnit(d: Double) {
def km = d * 1000.0
def m = d
def cm = d / 100.0
def mm = d / 1000.0
def ft = d / 3.28084
}
}
import Extensions.DoubleUnit
val oneInch = 25.4.mm
println(s"One inch is $oneInch meters")
// prints "One inch is 0.0254 meters"
val threeFeet = 3.ft
println(s"Three feet is $threeFeet meters")
// prints "Three feet is 0.914399970739201 meters"
网友评论