开发者

Is there example of scala abstract type usage which is impossible to achieve with generics?

开发者 https://www.devze.com 2023-04-10 10:02 出处:网络
There are two possible way to express abstraction over types. abstract class Buffer { type T val element: T

There are two possible way to express abstraction over types.

abstract class Buffer {
  type T
  val element: T
}

rather that generics, e.g.

abstract class Buffer[T] {
  val element: T
}

I understand benefits in usability开发者_如何转开发 of using different approaches in different contexts. But I'm interest in examples where it is absolutely impossible to convert Abstract Type version to Generic version.

PS Code snippets are welcome.


Abstract types can be bound to path dependent types which is not possible with type parameters. Thus you can e.g. implement an abstract type with a concrete inner class:

trait A { type T }
class B extends A { class T }

or explicitly bind it to a path dependent type inside the classes scope:

class C { type T = this.type }
class D { object Q; type T = Q.type }


Another difference: only type parameters can be used as self-types,

abstract class Buffer[T] { self: T =>
  val element: T
}


// This is possible
trait M { type TM }
trait P[TP] extends M { type TM = TP }

// This is not
trait P[TP]
trait M extends P[TM] { type TM }
0

精彩评论

暂无评论...
验证码 换一张
取 消