Scala cast to generic type (for generic numerical function)
NickName:sema Ask DateTime:2014-11-30T19:36:11

Scala cast to generic type (for generic numerical function)

I'm trying to implement a generic function that wraps a mathematical Java function. For simplicity, we can assume that the Java function (Java 7) takes one parameter and returns a result, both of type java.lang.Double. Of course, the wrapper function should take a parameter and a result, both of generic but numeric type A. The problem is that I'm not able to cast the result back to type A in the wrapper function. Where/what is the problem?

Note: (I'm a newbie on Scala and used the following reference to solve the problem.)

Variant A

package test

object mytest {
  def f[A](x: A)(implicit num: Numeric[A]): A = {
    val result = new java.lang.Double(num.toDouble(x))
    result.asInstanceOf[A]
  }

  def main(args: Array[String]) {
    // 'Some code'
  }
}

'Some code' A1

result val result = f(3)

Output:

Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
    at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:105)
    at test.mytest$.main(test.scala:10)
    at test.mytest.main(test.scala)

'Some code' A2

println(f(3))

Output:

3.0

'Some code' A3

println(f(3).getClass)

Output:

int

Variant B

package test

object mytest {
  def f[A : Manifest](x: A)(implicit num: Numeric[A]): A = {
    val result = new java.lang.Double(num.toDouble(x))
    manifest[A].erasure.cast(result).asInstanceOf[A]
  }

  def main(args: Array[String]) {
    val result = f(3)
  }
}

Output:

(This is the same also for equivalents of variants A1, A2, and A3, because the exception is now thrown in line 6 of function f.)

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Double to int
    at java.lang.Class.cast(Class.java:3176)
    at test.mytest$.f(test.scala:6)
    at test.mytest$.main(test.scala:10)
    at test.mytest.main(test.scala)

Copyright Notice:Content Author:「sema」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/27212776/scala-cast-to-generic-type-for-generic-numerical-function

More about “Scala cast to generic type (for generic numerical function)” related questions

Scala cast to generic type (for generic numerical function)

I'm trying to implement a generic function that wraps a mathematical Java function. For simplicity, we can assume that the Java function (Java 7) takes one parameter and returns a result, both of t...

Show Detail

to build a generic cast function in scala

I'd like to build a function to read the settings from a properties file, key/value pairs, and then cast it to expected types. If the given field name does't exist, we get the default value of the

Show Detail

scala generic function to convert "Any" type to specified generic type argument

Is it possible to write a generic function that accepts a value of type "Any" and a generic type argument say "T" and return Option[T] by checking runtime type of the value passed in ? I tried in...

Show Detail

Spark Scala generic min() function

How can I create a generic min() function in Spark which returns a value of the same type as the generic used? Here's what I have for doubles and strings: def minDouble(rdd: RDD[Map[String, Strin...

Show Detail

Casting a Generic type to AnyRef in Scala

I have a problem regarding type safety in scala. In fact, in Java I could cast a generic type to an Object. The annotation @SuppressWarning("unchecked") did the job. However in scala I am strugglin...

Show Detail

Scala cast to generic type

I'm confused about the generic type. I expect that 2.asInstanceOf[A] is cast to the type A, meanwhile, it's cast to Int. Besides that, the input is java.lang.Long whereas the output is a list of Int (

Show Detail

Scala Generic function assuming type

When trying to define a generic method def f[T] (x:T) = x + 1 Scala gives below error <console>:8: error: type mismatch; found : Int(1) required: String def f[T] (x:T) = x + 1 ...

Show Detail

Casting a Scala Object into a Generic type?

Firstly, some background: I'm currently writing a generic solver for a certain class of problems (specifically, a structural SVM solver) in Scala. In order to use this, the user has to implement an

Show Detail

Is there a way to cast to the type passed in a generic function?

I want to write a generic function, to loop through several different objects, that have one field in common. I want to change this field on all of the objects. However, I need the types of each ...

Show Detail

Scala generic Function vs Generic Method

So far i was under the impression that the only way to define Generic function in scala, was using Method e.g. def myToString[A](value: A) = {println(value)} However i figured the following way: val

Show Detail