以下代码片段来自twitter的Scala学派:
Scala has rank-1 polymorphism. Roughly, this means that there are some type concepts you’d like to express in Scala that are “too generic” for the compiler to understand. Suppose you had some function:
def toList[A](a: A) = List(a)
which you wished to use generically:
def foo[A, B](f: A => List[A], b: B) = f(b)
This does not compile, because all type variables have to be fixed at the invocation site. Even if you “nail down” type
B
,def foo[A](f: A => List[A], i: Int) = f(i) // Line 1
…you get a type mismatch.
为什么第 1 行会失败? B 的类型是已知的。为什么编译失败?
最佳答案
scala> def toList[A](a:A) = List(a)
toList: [A](a: A)List[A]
scala> def foo[A, B](f: A => List[A], b: B) = f(b)
<console>:10: error: type mismatch;
found : b.type (with underlying type B)
required: A
def foo[A, B](f: A => List[A], b: B) = f(b)
此行无法编译,因为当函数需要 A
类型的值时,您传递的是 B
类型的值。
def foo[A](f: A => List[A], i: Int) = f(i) // Line 1
对于这一行,您需要提供从类型 Int
到类型 A
的隐式转换。
关于Scala Rank-1 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31146926/