You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 hello takes a single parameter of type Any.
  • When you call it with empty parentheses (hello()), Scala doesn't throw an error—it automatically passes the only instance of the Unit type: ().
  • Since Any is the root of Scala's entire type hierarchy, every type (including Unit, which is an AnyVal) extends Any. That means () is a valid value for an Any parameter, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:02:49