scalaNewb
scalaNewb

Reputation: 11

Scala: type mismatch issue with type Any and templated class

I have the following problem with the scala type system and I have currently no idea how to fix this.

Basically there is the follow situation:

I have a class, lets call it Actor. This class is templated.

class Actor[T](){
    def setValue(value: T): Int = {
        //do something with value
    }
}

Another class has a method which iterates over a HashMap of the following type:

var newValues = new HashMap[String, Any]()

This HashMap will contain values of type Int and String. The Key of the HashMap identifies a concrete Actor class and ensures that the type of the value fits the templated Actor class it refers to.

A method of the other class iterates over this HashMap:

newValues.foreach(
    kv => {
        db.getActor(kv._1).setValue(kv._2) //db.getActor returns an Actor identified by kv._1
    }
)

Because the concrete value (kv._2) has the same datatype like the templated class has recieved during runtime, I thought the scala engine would be able to cast the any-type into its concrete subtype T.

But I get the following error during compilation:

found   : kv._2.type (with underlying type Any)
required: _$3 where type _$3
   db.getActor(kv._1).setValue(kv._2)

Does anybody know to fix this problem? I thought by using the super-type Any it would be possible to get around a switch-case and using asInstanceOf[T] of object Any.

Hope somebody can help me!

Upvotes: 1

Views: 444

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297320

The problem here is:

Because the concrete value (kv._2) has the same datatype like the templated class has recieved during runtime,

Says who?

The compiler couldn't prove, at compile time, that this is, indeed, true. And, basically, it doesn't trust you.

You can always use asIntanceOf to tell the compiler that you know better -- also known as aiming a gun at your foot. And I wonder what type db.getActor returns! I'm half-guessing existential.

Upvotes: 2

Related Questions