是否有理由在Scala中使用子类型作为类型参数?

ptr*_*zlo 6 scala

我想知道是否有充分的理由使用子类型作为函数类型参数?让我们考虑以下示例:

scala> trait Animal { def sound: String }
defined trait Animal

scala> def f1[T <: Animal](a: T) = a.sound
f1: [T <: Animal](a: T)String

scala> def f2(a: Animal) = a.sound
f2: (a: Animal)String
Run Code Online (Sandbox Code Playgroud)

f1f2有一些优势吗?

Vic*_*roz 5

我相信你的例子没有任何优势.类型参数通常用于连接代码的不同部分,但T由于它与任何内容都不匹配,因此有效地丢失了信息.考虑另一个例子:

def f1[T <: Animal](a: T) = (a.sound, a)

def f2(a: Animal) = (a.sound, a)
Run Code Online (Sandbox Code Playgroud)

现在T传递给返回类型的东西是不同的:

class Dog extends Animal { def sound = "bow-wow" }

f1(new Dog)
//> (String, Dog) = (bow-wow,Dog@141851fd)

f2(new Dog)
//> (String, Animal) = (bow-wow,Dog@5a1fe991)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以将其f1视为在编译时"实例化"的模板,并基于编译时参数类型有效地生成特定方法.因此,如果你想f1(new Dog)(String, Dog)需要的地方使用它将编译,而f2(new Dog)不是.