---
title: "Scada 使用二"
author: "tcspecial"
date: "2018-06-11T20:19:08Z"
tags: ["Scala", "协变"]
categories: ["编程语言"]
slug: "scada"
draft: false
lastmod: "2018-06-11T20:19:08Z"
id: 2424762
url: "https://tcspecial.iteye.com/blog/2424762"
---

1\. var & val

var 变量，可变

val 类似常量，不可变

 

2\. map/reduce

```
val list = List(1,2,3,4,5,6)
list.map( f => println(s"val: $f") )		// val:1 xxx val:6
val sum = list.reduce( (sum, n) => sum+n ) 	// 21
```

 

3\. 泛型

scala泛型设计太过复杂，泛型支持多个奇怪的操作符，如：&lt;: &gt;: &lt;%  T:class T:Ordering

 

3.1 上下边界 &lt;: &gt;:

A &lt;: B A是B的子类

```
// 基类
class Person(val name: String) {
	def talk(person: Person){
		println(this.name + " talk to " + person.name)
	}
}

// 派生类
class Worker(name: String) extends Person(name)

// 普通类
class Dog(val name: String)

/**
 * 泛型为[]
 * <: 上边界，指明本身及派生类
 */
class Club1[T <: Person](p1: T, p2: T){
	def communicate = p1.talk(p2)
}

// 测试代码
val p = new Person("Spark")
val w = new Worker("Scala")
new Club1(p, w).communicate			// 无参调用可省略()，输出: Spark talk to Scala
```

 

 3.2 view bound &lt;%

A &lt;% B A可以转化B，需要一个隐式转换函数。

```
// <%
class Club2[T <% Person](p1: T, p2: T){
	def communicate = p1.talk(p2)
}

// 隐式转换函数
implicit def dog2Person(dog: Dog) = new Person(dog.name)
val d = new Dog("Dog")
new Club2[Person](p, w).communicate		// 对象擦除至Object，需[object]强转。 输出：Spark talk to dog
```

 

3.3 逆变和协变 +T -T

+T  Container\[A]是Container\[B]的子类

```
// Earth
class Earth {
	def sound(){
		println("Hello")
	}
}

// Animal
class Animal extends Earth{
	override def sound() = {
		println("Animal sound")
	}
}

// Bird
class Bird extends Animal{
	override def sound() = {
		println("Bird sound")
	}
}

// Container
class Space[+T] {
	println("Hello space")
}

// 测试代码
var a = new Space[Animal]
a = new Space[Bird]		// Bird为Animal子类，ok
// a = new Space[Earth]	        // Earth为父类，error
```

 

 输出:

hello space

hello space