0
\$\begingroup\$

I'm new to Scala and I'm trying to write a generic function to convert from Int to any scalar.

For example:

val res: Float = convertInt[Float](12)
val res: Double = convertInt[Double](12)
//etc

I've achieved the following code:

  trait FromIntConverter[T]{
    def apply(int: Int): T
  }

  def convertInt[T](int: Int)(implicit converter: FromIntConverter[T]): T = converter(int)

  implicit val IntToIntConverter = new FromIntConverter[Int]{
    def apply(int: Int) = int
  }

  implicit val IntToFloatConverter = new FromIntConverter[Float]{
    def apply(int: Int) = int.toFloat
  }

  implicit val IntToDoubleConverter = new FromIntConverter[Double]{
    def apply(int: Int) = int.toDouble
  }
  //etc

Is it ok in regards to readability/brevity/performance?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's ok in regards of readability, but it can be shortened.

There is no need to create a dedicated trait FromIntConverter with implementations. All that can happen anonymously.

The convertInt function can take a function as implicit parameter:

def convertInt[T](i: Int)(implicit converter: Int => T) = converter.apply(i)

And all the implicit vals can become one-liners:

implicit def intToFloat(i: Int) = i.toFloat

implicit def intToDouble(i: Int) = i.toDouble

P.S. I discourage the use of int as variable name, that shouldn't collide with the Java type name.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.