문제

I've recently started playing with Scala (2.8) and noticed the I can write the following code (in the Scala Interpreter):

scala> var x : Unit = 10
x : Unit = ()

It's not obvious what's going on there. I really didn't expect to see any implicit conversion to Unit.

도움이 되었습니까?

해결책

See section "6.26.1 Value Conversions" in the Scala Language Specification version 2.8:

...

Value Discarding. 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; () }.

...

다른 팁

Anything can be converted to Unit. This is mostly necessary to support side-effecting methods which nonetheless return values, but where the return value is often ignored. For instance

import java.util.{List =>JList}

def remove2[A](foo: JList[A], a1:A, a2:A):Unit = {
    foo.remove(a1)
    foo.remove(a2)  //if you couldn't convert the (usually pointless) return value of remove to Unit, this wouldn't type
}

Well, anything can be converted to unit (which is its purpose). You can think of Unit as unit in the lattice of (sub)types, which means it is a supertype of everything. See Wikipedia article.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top