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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Aug 28, 2016 at 4:33
\$\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.

answered Aug 31, 2016 at 11:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.