Skip to content

Instantly share code, notes, and snippets.

@paulp
Forked from anonymous/clonetest.scala
Created August 23, 2010 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulp/545840 to your computer and use it in GitHub Desktop.
Save paulp/545840 to your computer and use it in GitHub Desktop.
trait Cloneable[+T <: AnyRef] extends AnyRef {
def create(): T
override def clone(): T = create()
}
class A(var a: Int) extends Cloneable[A] {
def create(): A = new A(a)
}
class B(aa: Int, var b: Int) extends A(aa) with Cloneable[B] {
override def create(): B = new B(a, b)
}
// i can make polymorphic methods by using a typebound of T <: Cloneable[T] now,
// but if i use a bound of A or B or A with Cloneable[T] or B with Cloneable[T] it fails, which is suboptimal
//
// scala> class Bip[T <: A with Cloneable[A]](x: T)
// defined class Bip
//
// scala> new Bip(new A(5))
// res0: Bip[A] = Bip@4d22366e
//
// scala> class Bip[T <: B with Cloneable[B]](x: T)
// defined class Bip
//
// scala> new Bip(new A(5))
// <console>:7: error: inferred type arguments [A] do not conform to class Bip's type parameter bounds [T <: B with Cloneable[B]]
// new Bip(new A(5))
// ^
//
// scala> new Bip(new B(5, 10))
// res2: Bip[B] = Bip@2448b7f
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment