Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Option method signature, function already defined in this scope

def createFloatBuffer(data: Option[Quaternion]*): Option[FloatBuffer] = data match {
  ...
}

def createFloatBuffer(data: Option[Vector3f]*): Option[FloatBuffer] = data match {
  ...
}

This code will not compile due to the two methods having the same method signature. None type would not know which method to call.

I could just rename the methods, however I would like to this overloading style in my code.

like image 952
miniwolf Avatar asked Mar 17 '26 18:03

miniwolf


1 Answers

After type erasure this two methods become createFloatBuffer(data: Option), and all types information is lost and not available at run time.

As a workaround I can suggest you to use TypeClass pattern.

case class Quaternion(v: Int)
case class Vector3f(v: Int)

case class FloatBuffer(v: Int)

sealed trait FloatBufferBuilder[T] {
  def createFloatBuffer(data: Option[T]): Option[FloatBuffer]
}

implicit object QuaternionFloatBufferBuilder extends FloatBufferBuilder[Quaternion] {
  def createFloatBuffer(data: Option[Quaternion]) = data.map(d => FloatBuffer(d.v))
}

implicit object Vector3fFloatBufferBuilder extends FloatBufferBuilder[Vector3f] {
  def createFloatBuffer(data: Option[Vector3f]) = data.map(d => FloatBuffer(d.v))
}

def createFloatBuffer[T : FloatBufferBuilder](data: Option[T]): Option[FloatBuffer] =
  implicitly[FloatBufferBuilder[T]].createFloatBuffer(data)


println(createFloatBuffer(Some(Quaternion(1))))
println(createFloatBuffer(Some(Vector3f(1))))

Magnet Pattern could also interesting for you: http://spray.io/blog/2012-12-13-the-magnet-pattern/

like image 165
Eugene Zhulenev Avatar answered Mar 19 '26 12:03

Eugene Zhulenev