Scala runs on...

  • JVM
  • JavaScript in your browser
  • Natively with LLVM beta

Scala in a Nutshell

点击下面的框,查看运行中的Scala!

Seamless Java Interop

Scala在JVM上运行,因此Java和Scala堆栈可以自由混合以实现完全无缝的集成.

Type Inference

因此,类型系统不会感到那么静止. 不要为类型系统工作. 让文字系统为您服务!

Concurrency & Distribution

对集合使用数据并行操作,对并行使用和分发使用参与者,对异步编程使用期货.

Author.scala
class Author(val firstName: String,
    val lastName: String) extends Comparable[Author] {

  override def compareTo(that: Author) = {
    val lastNameComp = this.lastName compareTo that.lastName
    if (lastNameComp != 0) lastNameComp
    else this.firstName compareTo that.firstName
  }
}

object Author {
  def loadAuthorsFromFile(file: java.io.File): List[Author] = ???
}
App.java
import static scala.collection.JavaConversions.asJavaCollection;

public class App {
    public List<Author> loadAuthorsFromFile(File file) {
        return new ArrayList<Author>(asJavaCollection(
            Author.loadAuthorsFromFile(file)));
    }

    public void sortAuthors(List<Author> authors) {
        Collections.sort(authors);
    }

    public void displaySortedAuthors(File file) {
        List<Author> authors = loadAuthorsFromFile(file);
        sortAuthors(authors);
        for (Author author : authors) {
            System.out.println(
                author.lastName() + ", " + author.firstName());
        }
    }
}

Combine Scala and Java seamlessly

Scala classes are ultimately JVM classes. You can create Java objects, call their methods and inherit from Java classes transparently from Scala. Similarly, Java code can reference Scala classes and objects.


在此示例中,Scala类Author实现Java接口Comparable<T>并与Java File . Java代码使用来自伴随对象Author的方法,并访问Author类的字段. 它还使用JavaConversions在Scala集合和Java集合之间进行转换.

类型推断
scala> class Person(val name: String, val age: Int) {
     |   override def toString = s"$name ($age)"
     | }
defined class Person

scala> def underagePeopleNames(persons: List[Person]) = {
     |   for (person <- persons; if person.age < 18)
     |     yield person.name
     | }
underagePeopleNames: (persons: List[Person])List[String]

scala> def createRandomPeople() = {
     |   val names = List("Alice", "Bob", "Carol",
     |       "Dave", "Eve", "Frank")
     |   for (name <- names) yield {
     |     val age = (Random.nextGaussian()*8 + 20).toInt
     |     new Person(name, age)
     |   }
     | }
createRandomPeople: ()List[Person]

scala> val people = createRandomPeople()
people: List[Person] = List(Alice (16), Bob (16), Carol (19), Dave (18), Eve (26), Frank (11))

scala> underagePeopleNames(people)
res1: List[String] = List(Alice, Bob, Frank)

Let the compiler figure out the types for you

Scala编译器对静态类型很聪明. 大多数时候,您不需要告诉它变量的类型. 相反,其强大的类型推断功能将为您解决它们.

在此交互式REPL会话(Read-Eval-Print-Loop)中,我们定义一个类和两个函数. 您可以观察到编译器会自动推断函数的结果类型以及所有中间值.

Concurrent/Distributed
val x = Future { someExpensiveComputation() }
val y = Future { someOtherExpensiveComputation() }
val z = for (a <- x; b <- y) yield a*b
for (c <- z) println("Result: " + c)
println("Meanwhile, the main thread goes on!")

Go Concurrent or Distributed with Futures & Promises

在Scala中,可以使用Future和Promise 处理数据,从而更轻松地并行化甚至分发您的应用程序.

在此示例中, Future{}构造异步计算其参数,并以Future[Int]返回异步结果的句柄. 将来完成时(即计算完成时),可以使用理解来注册新的回调(发布要执行的新操作). 由于所有这些操作都是异步执行的,没有阻塞,因此主程序线程可以在此期间继续执行其他工作.

Traits

将Java样式的接口的灵活性与类的功能结合在一起. 想一想原则上的多重继承.

Pattern Matching

考虑"切换"类固醇. 与类层次结构,序列等进行匹配.

Higher-order functions

函数是一流的对象. 以保证类型安全的方式编写它们. 在任何地方使用它们,并将它们传递给任何东西.

Traits
abstract class Spacecraft {
  def engage(): Unit
}
trait CommandoBridge extends Spacecraft {
  def engage(): Unit = {
    for (_ <- 1 to 3)
      speedUp()
  }
  def speedUp(): Unit
}
trait PulseEngine extends Spacecraft {
  val maxPulse: Int
  var currentPulse: Int = 0
  def speedUp(): Unit = {
    if (currentPulse < maxPulse)
      currentPulse += 1
  }
}
class StarCruiser extends Spacecraft
                     with CommandoBridge
                     with PulseEngine {
  val maxPulse = 200
}

Flexibly Combine Interface & Behavior

在Scala中,可以将混合到一个类中,以结合其界面和行为.

在这里, StarCruiser是一艘Spacecraft ,它的CommandoBridge知道如何与飞船接合(提供了加速的手段),而PulseEngine则指定了如何加速.

Switch on the structure of your data

在Scala中, 案例类用于表示结构数据类型. 他们隐式地为类配备了有意义的toStringequalshashCode方法,以及通过模式匹配进行解构的能力.


在此示例中,我们定义了一小堆案例类,它们代表整数的二进制树(此处为简单起见,省略了通用版本). 在inOrdermatch构造根据t的类型选择正确的分支,同时解构Node的参数.

模式匹配
// Define a set of case classes for representing binary trees.
sealed abstract class Tree
case class Node(elem: Int, left: Tree, right: Tree) extends Tree
case object Leaf extends Tree

// Return the in-order traversal sequence of a given tree.
def inOrder(t: Tree): List[Int] = t match {
  case Node(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r)
  case Leaf          => List()
}

Go Functional with Higher-Order Functions

在Scala中,函数是值,可以使用简洁的语法将其定义为匿名函数.

Scala
val people: Array[Person]

// Partition `people` into two arrays `minors` and `adults`.
// Use the anonymous function `(_.age < 18)` as a predicate for partitioning.
val (minors, adults) = people partition (_.age < 18)
Java
List<Person> people;

List<Person> minors = new ArrayList<Person>(people.size());
List<Person> adults = new ArrayList<Person>(people.size());
for (Person person : people) {
    if (person.getAge() < 18)
        minors.add(person);
    else
        adults.add(person);
}

Run Scala in your browser

Scastie是您浏览器中的Scala + sbt ! 您可以使用任何版本的Scala,甚至可以使用备用后端,例如Dotty,Scala.js,Scala Native和Typelevel Scala. 您可以使用任何已发布的库. 您可以与任何人保存和共享Scala程序/内部版本.

交互运行Scala代码

Online Courses

Functional Programming Principles in Scala

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Functional Program Design in Scala

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Parallel Programming

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Big Data Analysis with Scala and Spark

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Functional Programming in Scala Capstone

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Programming Reactive Systems

  • 免费(可选的付费证书)
  • 每两周开始新的会话!

Upcoming Training

Scala ecosystem

Scala库索引(或Scaladex)表示所有已发布的Scala库的地图. 使用Scaladex,开发人员现在可以查询超过175,000个Scala库版本. Scaladex得到Scala中心的正式支持.

The Scala Library Index

Twitter Feed

查看更多推文,或

Follow Scala on twitter

The Scala language is maintained by

  • Scala Center
  • Lightbend

Scala Center is supported by

EPFL IBM Verizon Goldman Sachs 47 Degrees SAP Twitter Your company

by  ICOPY.SITE