时间:2023-02-07 10:03:56

Scala Overview

Scala is object-oriented

<Scala><For beginners>

  • Every user-defined class in Scala implicitly extends the trait scala.ScalaObject.
  • If Scala is used in the context of a Java runtime environment, then scala.AnyRef corresponds to java.lang.Object.

Scala is Functional

Anonymous Function Syntax

  • eg:
    (x: Int) => x + 1
    This is a shorthand for the following anonymous class definition:
    new Function1[Int, Int] {
    def apply(x: Int): Int = x + 1
    }
  • It is also possible to define functions with multiple parameters:

    (x: Int, y: Int) => "(" + x + ", " + y + ")"
    
  • or even with no parameter:

    () => { System.getProperty("user.dir") }

Higher-Order Functions

  • Higher-order functions are those who can take functions as parameters, or whose result is a function.
  • Eg: Function apply which takes another function f and a value v and applies function f to v:
    def apply(f: Int => String, v: Int) = f(v)
  • A more complicated example:
    class Decorator(left: String, right: String) {
    def layout[A](x: A) = left + x.toString() + right
    } object FunTest extends Application {
    def apply(f: Int => String, v: Int) = f(v)
    val decorator = new Decorator("[", "]")
    println(apply(decorator.layout, 7))
    }

  In this example, the method decorator.layout is coerced automatically to a value of type Int => String as required by method apply. Please note that the method decorator.layout is a polymorphic method(i.e. it abstracts over some of its signature types) and the Scala compiler has to instantiate its method type first appropriately.

Nested Functions

  • In Scala it is possible to nest function definitions.
  • Eg:
    object FilterTest extends Application {
    def filter(xs: List[Int], threshold: Int) = {
    def process(ys: List[Int]): List[Int] =
    if (ys.isEmpty) ys
    else if (ys.head < threshold) ys.head :: process(ys.tail)
    else process(ys.tail)
    process(xs)
    }
    println(filter(List(1, 9, 2, 8, 3, 7, 4), 5))
    }

Currying

  • Methods may define multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.
  • Eg:
    object CurryTest extends Application {
    def filter(xs: List[Int], p: Int => Boolean): List[Int] =
    if (xs.isEmpty) xs
    else if (p(xs.head)) xs.head :: filter(xs.tail, p)
    else filter(xs.tail, p) def modN(n: Int)(x: Int) = ((x % n) == 0) val nums = List(1, 2, 3, 4, 5, 6, 7, 8)
    println(filter(nums, modN(2)))
    println(filter(nums, modN(3)))
    }

    Note that method modN is partially applied in the two filter calls; i.e. only its first argument is actually applied. The term modN(2) yields a function of type Int => Boolean and is thus a possible candidate for the second argument of function filter.

Case Classes

    • Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.
    • An example for a class hierarchy which consists of an abstract super class Term and three concrete case classes Var, Fun and App.
      abstract class Term
      case class Var(name: String) extends Term
      case class Fun(arg: String, body: Term) extends Term
      case class App(f: Term, v: Term) extends Term
    • This class hierarchy can be used to represent terms of the untyped lambda calculus.
    • To facilitate the construction of case class instances, Scala does not require that the new primitive is used.
    • The main benefits of case class:
      • Dont need new when initialization;
      • better toString() method;
      • with equals() & hashCode() default;
      • with Serializable default;
      • The constructor parameters are public(can be access directly);
      • Support pattern matching;(It makes only sense to define case classes if pattern matching is used to decompose data stuctures.)
    • For better understanding of case class, u should know pattern matching first:
      • For javaer, switch is some kind of pm, but it's easy for programmer to forget 'break';
      • But in scala: [Scala has a built-in general pattern matching mechanism. It allows to match on any sort of data with a first-match policy. ]
        object PatternMatchingTest extends App {
        for (i <- 1 to 100) {
        i match {
        case 10 => println(10)
        case 50 => println(50)
        case _ =>
        }
        }
        }

Case class can be seen as a special class that have been optimized for pattern matching

      .
abstract class Person

case class Student(name: String, age: Int, studentNo: Int) extends Person
case class Teacher(name: Stirng, age: Int, teacherNo: Int) extends Person
case class Nobody(name: String) extends Person object CaseClassDemo {
def main(agrs: Array[String]): Unit = {
// case class will generate apply method, this can reduce 'new'
val p: Person = Student("john", 18, 1024) // match case
p match {
case Student(name, age, studentNo) => println(name + ":" + age + ":" + studentNo)
case Teacher(name,age,teacherNo)=>println(name+":"+age+":"+teacherNo)
case Nobody(name)=>println(name)
}
}
}

当一个类被声明为case class时,scala会帮我们做以下几件事情:

    • 自动创建伴生对象,同时在其内实现子apply方法,因为在使用时不用显式new;
    • 伴生对象内同时实现了upapply(),从而可以将case class用于模式匹配,具体之后在extractor会介绍;
    • 实现toString(), hashCode(), copy(), equals()

Extractor Objects

    • In scala, patterns can be defined independently of case classess. To this end, a method named unapply is defined to yield a so-called extractor.
    • For instance, the following code defines an extractor object `Twice`.

object Twice {
def apply(x: Int): Int = x * 2
def unapply(z: Int): Option[Int] = if (z % 2) == 0 Some(z / 2) else None
} object TwiceTest extends Application {
val x = Twice(21)
x match { case Twice(n) => Console.println(n) }
}

There are two syntactic conventions at work here:

    • The pattern case Twice(n) will cause an invocation of Twice.unapply, which is used to match even number; the return value of the unapply signals whether the argument has matched or not, and any sub-values that can be used for further matching. Here, the sub-value is z/2.
    • The apply method is not necessary for pattern matching. It is only used to mimick a constructor. val x = Twice(21) expands to val x = Twice.apply(21).
  • The return type of an unapply should be chosen as follows:
    • If it is just a test, return a Boolean.
    • If it returns a single sub-value of type T, return a Option[T].
    • If u want to return several sub-values T1, ..., Tn, group them in an optional tuple Option[(T1, ..., Tn)].
  • Extractor: 提取器是从传递给它的对象中提取出构造该对象的参数。Scala提取器是一个带有unapply方法的对象。unapply方法算是apply方法的反向操作:unapply方法接受一个对象,然后从对象中提取值,提取的值通常是用来构造该对象的值。

Scala is statically typed

  • Scala is equipped with an expressive type system that enforces statically that abstractions are used in a safe and coherent manner.
  • In particular, the type system supports:
    • generic classes
    • variance annotations
    • upper and lower type bounds
    • inner classes and abstract types as object members
    • compound types
    • explicitly typed self references
    • vies
    • polymorphic methods

Generic classes

  • Scala has built-in support for classes parameterized with types. Such generic classes are particularly useful for the development of collection classes.
  • Eg:
    class Stack[T] {
    var elems: List[T] = Nil
    def push(x: T) { elems = x :: elems }
    def top: T = elems.head
    def pop() { elems = elems.tail }
    }

    The use of type parameters allows to check that only legal elements(that of type T) are pushed onto the stack.

  • Note that subtyping of generic types is invariant. This means that if we have a stack of characters of type Stack[Char] then it cannot be used as an integer stack of type Stack[Int].

Variances

  • Scala supports variance annotations of type parameters of generic classes.

<Scala><For beginners>的更多相关文章

  1. SCALA XML pattern attrbute&lpar;属性&rpar;

    from: Working with Scala's XML Support 虽然这个guy炒鸡罗嗦,但是还是讲到我要的那句话:  Because Scala doesn't support XML ...

  2. Docker on CentOS for beginners

    Introduction The article will introduce Docker on CentOS. Key concepts Docker Docker is the world's ...

  3. jdb调试scala代码的简单介绍

    在linux调试C/C++的代码需要通过gdb,调试java代码呢?那就需要用到jdb工具了.关于jdb的用法在网上大家都可以找到相应的文章,但是对scala进行调试的就比较少了.其实调试的大致流程都 ...

  4. scala练习题1 基础知识

    1, 在scala REPL中输入3. 然后按下tab键,有哪些方法可以被调用? 24个方法可以被调用, 8个基本类型: 基本的操作符, 等:     2,在scala REPL中,计算3的平方根,然 ...

  5. 牛顿法求平方根 scala

    你任说1个整数x,我任猜它的平方根为y,如果不对或精度不够准确,那我令y = (y+x/y)/2.如此循环反复下去,y就会无限逼近x的平方根.scala代码牛顿智商太高了println( sqr(10 ...

  6. Scala集合和Java集合对应转换关系

    作者:Syn良子 出处:http://www.cnblogs.com/cssdongl 转载请注明出处 用Scala编码的时候,经常会遇到scala集合和Java集合互相转换的case,特意mark一 ...

  7. Scala化规则引擎

    1. 引言 什么是规则引擎 一个业务规则包含一组条件和在此条件下执行的操作,它们表示业务规则应用程序的一段业务逻辑.业务规则通常应该由业务分析人员和策略管理者开发和修改,但有些复杂的业务规则也可以由技 ...

  8. Scala快速概览

    IDEA工具安装及scala基本操作 目录 一. 1. 2. 3. 4. 二. 1. 2. 3. 三. 1. 2. 3. 4. 5. 6. 7. 四. 1. (1) (2) (3) (4) (5) ( ...

  9. Scala Macros - scalamela 1&period;x,inline-meta annotations

    在上期讨论中我们介绍了Scala Macros,它可以说是工具库编程人员不可或缺的编程手段,可以实现编译器在编译源代码时对源代码进行的修改.扩展和替换,如此可以对用户屏蔽工具库复杂的内部细节,使他们可 ...

随机推荐

  1. MySQL For Windows Zip解压版安装

    前言 Windows 下 MySQL 有msi和zip解压安装版两种,而zip版只需解压并做简单配置后就能使用,我个人比较喜欢这种方式. 注意我们这里说的MySQL是指MySQL服务器,有很多初学的同 ...

  2. 分享一个Jquery 分页插件 Jquery Pagination

    分页插件来说,我觉得适用就行,尽量简单然后能够根据不同的应用场景能够换肤.展现形式等. 对于初学者想写分页插件的同学,也可以看下源码,代码也挺简单明了的,也助于自己写个小插件. 不过我比较懒,一般直接 ...

  3. ThinkPHP框架的部署

    1.将ThinkPHP框架的框架文件放到想要放置的地方,与创建的应用文件夹同级 2.vhost文件中设置虚拟目录 3.在hosts文件中配置 4.在应用目录中创建入口文件index.php 5.在入口 ...

  4. Wordnet 与 Hownet 比较

    近年来,随着计算机本身以及信息高速公路的飞速发展,人们开始更加重视语义的研究.各国都致力于可用于自然语言处理的大规模语义词典或大规模知识库的建设.例如:普林斯顿大学的英语Wordnet,微软的Mind ...

  5. hdu 5199 Gunner(STL之map,水)

    Problem Description Long long ago, there is a gunner whose name is Jack. He likes to go hunting very ...

  6. Python操作 Memcache、Redis、RabbitMQ

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  7. JavaWeb项目架构之NFS文件服务器

    NFS简介 NFS(Network File System)即网络文件系统. 主要功能:通过网络(局域网)让不同的主机系统之间可以共享文件或目录. 主要用途:NFS网络文件系统一般被用来存储共享视频, ...

  8. spy&lpar;主席树&rpar;

    题目链接 题目为某次雅礼集训... 对于\(\max\{a-A_i,\ A_i-a,\ b-B_i,\ B_i-b\}\),令\(x_1=\frac{a+b}{2},\ y_1=\frac{a-b}{ ...

  9. 深夜一次数据库执行SQL思考(怎么看执行报错信息)

    如下sql在执行时 DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, ` ...

  10. Linux基础命令---忽略挂起信号nohup

    nohup nohup可以使程序能够忽略挂起信号,继续运行.用户退出时会挂载,而nohup可以保证用户退出后程序继续运行.如果标准输入是终端,请将其从/dev/null重定向.如果标准输出是终端,则将 ...