如何隐式转换为单位?

How to convert implicitly to Unit?

是否可以对给定对象执行隐式 自定义Unit 的转换?

我的意思是像这样定义一个转换:

implicit def toUnit(m: MyClass): Unit = println("Hello")

并按如下方式使用它:

val x: MyClass = new MyClass() // no conversions
val y: Unit = new MyClass() // 1
new MyClass() // 2

我已经像上面那样定义了一些到其他对象的转换:Unit 是唯一的 class 不起作用。

我认为它应该可以工作,至少在 1 的情况下是这样,但我看不到 Hello 打印在控制台上。为什么?

这是行不通的,因为 Unit 是由编译器专门处理的。由于值丢弃,您可以将 MyClass 分配给 Unit。没有涉及隐式。

来自scala spec

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }.

所以这里发生的是 new MyClass() 被编译器更改为

{ new MyClass(); () }