Scala Rank-1 多态性

标签 scala

以下代码片段来自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/

相关文章:

scala - 如何在 scala 中模拟 Unit 方法

scala - 有没有办法获取 mesos 中任务使用的最大内存?

azure - Spark 3.3(scala)中UDF函数的问题

scala.io.Source.fromInputStream 不会进一步抛出 MalformedInputException

java - 在scala中,如何提取DynamicVariable中的值?

Scala + Play Framework + Slick + Akka - 来自 Akka Actor 的数据库访问

scala - 映射操作中的元组解包

scala - Scala 脚本可以引用同一目录中其他未编译的 scala 代码吗?

xml - 如何使用 Scala 获取与唯一节点相邻的节点?

scala - 使用 Map 替换 Spark 中的列值