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

3

15

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.

Skid answered 30/9, 2011 at 21:0 Comment(0)
W
10

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 }
Wennerholn answered 30/9, 2011 at 22:27 Comment(0)
M
5

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

abstract class Buffer[T] { self: T =>
  val element: T
}
Mertens answered 1/10, 2011 at 4:47 Comment(0)
W
2
// 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 }
Wenwenceslaus answered 30/9, 2011 at 21:50 Comment(1)
But what actually I can't do with generics? 1. example easily can be converted to "trait M[TM]; trait P[TP] extends M[TP]". 2. Simply does not compile so nothing to convert...Skid

© 2022 - 2024 — McMap. All rights reserved.