Reputation: 16628
I am getting following error message:
[error] found : AnyVal
[error] required: Int
But Int
extends AnyVal [1]
so I believe as in Java
, Integer
can be casted from Object
why it's not working in Scala
, what I am missing:
[1] final abstract class Int private extends AnyVal
I also tried with a simple example:
val a: AnyVal = 5
def aTob(a: Int): Int = a * 5
aTob(a)
Error:(5, 73) type mismatch;
found : AnyVal
required: Int
But following works:
val a: Any = 5
def aTob(a: Int): Int = a * 5
aTob(a.asInstanceOf[Int])
I don't want to explicitly cast it, but it should be implicit casting.
[Edit:] I also tried with
Any
-
Update:
def getValue(dType: String): Any = {
dType.toLowerCase() match {
case "double[3]" =>
10d
case "float" =>
1f
}
val d = getValue("double[3]")
val f = getValue("float")
SomeClass(d, f)
case class SomeClass(val d : Double, val f: Float)
Upvotes: 0
Views: 1152
Reputation: 1572
You can use implicit conversion, but it is prone to error because you if you pass e.g. Float
like val a: AnyVal = 5.0F
you will get ClassCastException
:
implicit def anyValToInt(anyVal: AnyVal): Int = anyVal.asInstanceOf[Int]
val a: AnyVal = 5
def aTob(a: Int): Int = a * 5
aTob(a)
Upvotes: 1