您的位置:首页 > 其它

Scala in depth 6 Scala的类型系统 下

2014-12-28 09:36 330 查看
接上一篇。

1. Java中是否也有声明Upper bound 和 Lower boud的语法呢? 有的,比如:

List<E extends Numeric> List<E upper Integer>

2.Java中的 List<?> 和 List<Object> 有什么区别?
List<?> 代表 任意类型的 List都可以赋值给它
List<Object> 代表 List中元素的类型是任意的
package tstge;
import java.util.*;
public class Tst {
public static void main(String[] args) {
ArrayList<?> mylist1 = null;
ArrayList<Object> mylist2 = null;
ArrayList<Integer> mylist3 = new ArrayList<Integer>();
mylist2 = mylist3; // Error! type mismatch: cannot convert from ArrayList<Integer> to ArrayList<Object>
mylist1 = mylist3;
}
}


3.Java的类型通常可以直接翻译成scala的类型。但是像 Iterator<?>, Iterator<? extends Component> 这样的类型怎么翻译呢?
Iterator[T] forSome { type T } 或 Iterator[_]
Iterator[T] forSome { type T <: Component }

关于forSome,Stack Overflow有个贴子介绍的很好:
http://stackoverflow.com/questions/15186520/scala-any-vs-underscore-in-generics

4.View bound

def foo[A <% B](x: A) = x
意思是在调用foo方法的地方,必须能看到从A类型到B类型的转换函数,相当于
def foo[A](x: A)(implicit $ev0: A => B) = x

5. Context bound

def foo[A : B](x: A) = x
The foo method defines a constraint A : B. This constraint means that the parameter
x is of type A and there must be an implicit value B[A] available when calling method
foo. Context bounds can be rewritten as follows

def foo[A](x: A)(implicit $ev0: B[A]) = x
当前上下文必须存在类型为B[A]的隐含值

示例:
def tabulate[T: ClassManifest](len: Int, f: Int => T) = {
val xs = new Array[T](len)
for (i <- 0 until len) xs(i) = f(i)
xs
}
会被展开成
def tabulate[T](len: Int, f: Int => T)(implicit m: ClassManifest[T]) = {
val xs = new Array[T](len)
for (i <- 0 until len) xs(i) = f(i)
xs
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: