Scala: forSome关键字

forSome是Scala的一个关键字,不是函数。

在Scala的changeLog中,关于forSome的描述:

“It is now possible to define existential types using the new keyword forSome. An existential type has the form T forSome {Q} where Q is a sequence of value and/or type declarations. “

forSome用于下面的场景:
我们想对一些对象做一些操作,但是不关心对象内部的具体类型。或者说我们指向知道对象可以进行哪些操作,但是不关心它是什么以及可以进行哪些其他操作。比如我们想取List的第一个元素或者List的长度,但是不关心List是什么类型。因此我们需要知道该对象可以进行获取长度的操作,但是不关心其元素是什么类型:

Hence, there are useful existential types which hide some of the structure of the objects they represent but show enough structure to allow manipulations of the objects through operations the objects themselves provide

即Existential type做到了隐藏我们不关心的对象结构,同时暴露我们想要进行的操作,恰如其分地对外暴露协议。

def printFirst(x : Array[T] forSome {type T}) = println(x(0)) 

我们也可以使用泛型:

def printFirst[T](x : Array[T]) = println(x(0)) 

但是有些情况下我们可能不想使用方法泛型。

来自scala的术语表:

An existential type includes references to type variables that are unknown. For example, Array[T] forSome { type T } is an existential type. It is an array of T, where T is some completely unknown type. All that is assumed about T is that it exists at all. This assumption is weak, but it means at least that an Array[T] forSome { type T } is indeed an array and not a banana.

也就是说forSome只是表面类型存在,至于它是什么类型,不关心,Java中我们这样定义泛型:

class MyClass<?> {
    ...
}

也就是我们不关心泛型的类型,任何类型都可以。

另外可以指定某些类型,类似于Java中的

def addToFirst(x : Array[T] forSome {type T <: Integer}) = x(0) + 1
class MyClass<? extends Integer> {
    ...
}

一种更简洁的写法:

def addToFirst(x: Array[_ <: Integer ]) = x(0) + 1

对于下面两个例子:

Array[T] forSome { type T; }
Array[T forSome { type T; }]

他们之间的区别非常大,第一个代表元素类型为任意类型的Array,第二个代表Array[Any]。即:T forSome {type T;} 等同于Any。

Type Any is equivalent to a for_some { type a; }

再看:

Map[Class[T forSome { type T}], String]  // Map[Class[Any],String]
Map[Class[T] forSome { type T}, String]  // key为任意类型的Class
Map[Class[T], String] forSome { type T}

使用通配符:

Array[_]               // Array[T] forSome {type T}
Map[Class[_] , String] //Map[Class[T] ,String] forSome {type T}

有用链接

1) StackOverflow :What is the forSome keyword in Scala for?

2) Scala语言规范:existensial type

3) 博客:Scala existensial types

4) 另一篇博客: existensial type

5) 又一篇博客: Existensial与模式匹配

6) Scala 术语表

你可能感兴趣的:(scala)