Nicola Ferraro
Nicola Ferraro

Reputation: 4189

How to convert implicitly to Unit?

Is it possible to execute an implicit custom conversion to Unit for a given object ?

What I mean is defining a conversion like:

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

And using it as follows:

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

I have defined some conversions to other objects as above: Unit is the only class that is not working.

I think it should work, at least in case 1, but I can't see Hello printed on the console. Why ?

Upvotes: 2

Views: 72

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

This won't work because Unit is handled specially by the compiler. You're able to assign MyClass to Unit because of value discarding. There are no implicits involved.

From the 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; () }.

So what happens here is that new MyClass() is changed by the compiler to

{ new MyClass(); () }

Upvotes: 4

Related Questions