In Scala, many types extend Any. Click here for a diagram of the Scala Class Hierarchy.
For instance, Double and Tuple both extend Any and the code below works as expected:
def foo(x: Any) { println(x.toString) }
foo(3.0) // prints: 3.0
foo((2,3)) //prints: (2,3)
However, I don't understand why the following doesn't work, since it follows all the logic above:
def bar(fn: Any => String) { println(fn.toString) }
def dub(d: Double): String = "dub"
def tup(tup: (Int, Int)): String = "tup"
bar(dub) // ERROR
bar(tup) // ERROR
Calling bar(dub) and bar(tup) both result in a type mismatch error. For bar(dub) the compiler says:
error: type mismatch;
found: Double => String
required: Any => String
Can someone explain to me why there is a type mismatch in the second case even though Any is a supertype?