简体   繁体   English

我为什么要使用类型T = <type> 而不是特征[T]?

[英]Why would I use type T = <type> instead of trait[T]?

Here is an observation I've had from a chapter in Programming Scala . 这是我从《 Scala编程》 一章中获得的观察结果。

In Scala, I often see the abstract trait pattern: 在Scala中,我经常看到抽象特征模式:

trait Abstract {
  type T
  def transform(x: T): T
  val initial: T
  var current: T
}

class Concrete extends Abstract {
  type T = String
  def transform(x: String) = x + x
  val initial = "hi"
  var current = initial
}

Why would I choose the abstract trait pattern over parameterized generics? 为什么我会选择抽象特征模式而不是参数化泛型?

trait Abstract[T] {
  def transform(x: T): T
  val initial: T
  var current: T
}

class Concrete extends Abstract[String]{
  def transform(x: String): x + x
  val initial: "hi"
  var current: initial
}

The two approaches are mostly equivalent. 两种方法大致相同。 One reason we might prefer a type member is so that methods can be written with dependent types rather than having to be generic: 我们可能更喜欢类型成员的一个原因是,方法可以用依赖类型来编写,而不必是通用的:

def doSomethingWith(a: Abstract): a.T = ...

is arguably more readable than 可以说比

def doSomethingWith[T](a: Abstract[T]): T = ...

at least as the signatures get more complicated (particularly if we're doing type-level programming, using Abstract as a type-level function). 至少随着签名变得更加复杂(特别是如果我们在进行类型级编程时,使用Abstract作为类型级函数)。

There might be also implications for type inference; 类型推断可能还会有一些含义。 I don't know precisely how scala type inference works, but as far as I can tell there's no way to partially specify the types of a function: 我不知道scala类型推断的工作原理,但是据我所知,无法部分指定函数的类型:

def functionWeWantToCall[U, V, W](a: Abstract[U], b: Abstract[V], c: Abstract[W])
functionWeWantToCall[String, _, _](x, y, z) //won't compile

def functionWeWantToCall(a: Abstract, b: Abstract, c: Abstract)
functionWeWantToCall(x: Abstract{type T = String}, y, z) //works

So that's a reason I've sometimes found myself using the type member approach. 所以这就是我有时发现自己使用类型成员方法的原因。

Also, of course, some people (eg those from an ML background) simply find the type member approach more familiar or readable. 同样,当然,有些人(例如,来自ML背景的人)只是觉得类型成员方法更熟悉或更易读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM