Scala type bound on implemented function

106 Views Asked by At

I have a generic class that looks like:

class GenericClass[T <: AnyRef] {
  def getHash(obj: T): String = obj.toString
}

As you can see, type T needs to have implemented the toString function in order for getHash to work properly. My question: is that possible to apply type bound/constraints so that type T always have toString implemented?

One way that I can think of is to use type class and context bound:

class GenericClass[T : ClassWithToString] {...}


trait ClassWithToString[T] {
  def toString(t: T): String
}

implicit object SomeTypeWithToString extends ClassWithToString[SomeType] {
  override def toString(a: SomeType): String = a.toString()
}

However, this approach requires clients to define new implicit objects whenever they want to use GenericClass with a new type, which is not ideal in my case. Especially given toString is a very common function that's being implemented by many types. Wanted to get some advice from you on how to solve this issue elegantly!

1

There are 1 best solutions below

0
foxys On

Yes, there is such type boundery, search for Structural Types.

class GenericClass[T <: { def myFunction(): String }] {
  def getHash(obj: T): String = obj.myFunction()
}

class MyClass {
  def myFunction(): String = "Hello"
}

val genericClass = new GenericClass[MyClass]

println(genericClass.getHash(new MyClass))