0

Please take a look at this function in Scala and tell me why it doesn't compile.

def alternative_identity[A <: Any, B <: Any](obj: A): B = { obj } 

I know that the function itself doesn't make sense, however I am trying to solve more complex problem and this example illustrates the fundamental problem which I have. Thank you in advance!

4
  • How is the compiler supposed to know what B is? The function is supposed to return B, but it's returning A. Are they supposed to have the same type? What is the function supposed to do? Commented Jan 21, 2015 at 18:30
  • But compiler knows that obj is a subtype of Any, because A is subtype of Any. Then compiler can infer that obj satisfies requirements for B (being subtype of Any). What is wrong in this reasoning? Commented Jan 21, 2015 at 18:34
  • 1
    What if I call alternative_identity[Int, Process](1) ? How on earth will an Int magically become a Process? Commented Jan 21, 2015 at 18:45
  • 2
    @PiotrNiedzwiedz - Monkeys are animals and Rhinos are animals, but Monkeys are not Rhinos. Commented Jan 21, 2015 at 18:47

1 Answer 1

4

It does not compile because obj is object of type A and you are returning it from a function where the return type is B

Even though A and B is subtype ofAny there is no way to know whether B is the base class of A.

For example, String and Int are subtypes of Any but they can't be used interchangeably.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.