Scala中为何可无参调用接收Any参数的方法?且为何返回true?
解答你的Scala方法调用疑问
Hey folks, let's unpack your two Scala questions clearly—they're linked by a neat little language quirk that trips up a lot of new Scala devs!
问题1:为何调用接收Any类型参数的方法时不传参是合法的?
This boils down to a Scala language feature tied to method calls and the Unit type:
- Your method
hellotakes a single parameter of typeAny. - When you call it with empty parentheses (
hello()), Scala doesn't throw an error—it automatically passes the only instance of theUnittype:(). - Since
Anyis the root of Scala's entire type hierarchy, every type (includingUnit, which is anAnyVal) extendsAny. That means()is a valid value for anAnyparameter, so the call is completely legal.
问题2:为什么无参调用hello方法返回true?
Let's walk through the code step by step with the actual parameter being passed:
class Bla { def hello(x: Any): Boolean = x.toString.length == 2 } // When you call new Bla().hello(), you're really doing this under the hood: new Bla().hello(())
Now, what's the result of ().toString? If you test this in the Scala REPL, you'll see it returns the string "()"—which has a length of exactly 2.
Your method checks if the length of x.toString equals 2, so this condition evaluates to true—hence the output you see.
内容的提问来源于stack exchange,提问作者Jagat
相关产品推荐
相关产品推荐

