[英]how to know Return type inferred in scala
val a=10; val b=if(a==5) println("hello") else (1,"hi")
What will be return type inferred in this case?在这种情况下将推断返回类型是什么? And How?
如何?
Presumably you're asking for the type of b
, which in this case is Any
.大概您要求的是
b
的类型,在这种情况下是Any
。
if (a == 5) println("hello") else (1, "hi")
gets typed as follows:输入如下:
For an if
expression, the type is the least upper bound of the two possible branches: if the consequent expression ( println("hello")
in this case) has type A
and the alternative expression ( (1, "hi")
) has type B
, then it is the type C
such that A
and B
are both non-strict subtypes of C
and there is no type D
which is a strict subtype of C
where A
and B
are non-strict subtypes of D
(non-strict means that we can consider a type to be a subtype of itself; strict means we can't).对于
if
表达式,类型是两个可能分支的最小上界:如果结果表达式(本例中为println("hello")
)具有类型A
并且替代表达式( (1, "hi")
)具有类型B
,那么它是类型C
使得A
和B
都是C
非严格子类型,并且没有类型D
是C
的严格子类型,其中A
和B
是D
非严格子类型(非严格意味着我们可以将类型视为其自身的子类型;严格意味着我们不能)。
The type of println("hello")
is Unit
println("hello")
的类型是Unit
The type of (1, "hi")
is a Tuple2[Int, String]
(1, "hi")
是一个Tuple2[Int, String]
Unit
's supertypes are AnyVal
and Any
Unit
的超类型是AnyVal
和Any
Tuple2
's supertypes are Serializable
, Product2[Int, String]
, Product
, Equals
, AnyRef
, and Any
(technically, Product2
's and Tuple2
's covariance means that there are some more supertypes (eg Tuple2[AnyVal, String]
, Tuple2[Int, AnyRef]
, Tuple2[Any, Any]
), but those don't end up being relevant here) Tuple2
的超类型是Serializable
、 Product2[Int, String]
、 Product
、 Equals
、 AnyRef
和Any
(从技术上讲, Product2
和Tuple2
的协方差意味着有更多的超类型(例如Tuple2[AnyVal, String]
、 Tuple2[Int, AnyRef]
, Tuple2[Any, Any]
),但这些最终与此处无关)
The least-upper-bound is therefore Any
, so the type of the if
expression and thus of b
is Any
因此最小上界是
Any
,所以if
表达式的类型以及b
是Any
You can demonstrate this in a REPL, eg sbt console
您可以在 REPL 中演示这一点,例如
sbt console
scala> :paste
// Entering paste mode (ctrl-D to finish)
val a=10; val b=if(a==5) println("hello") else (1,"hi")
// Exiting paste mode, now interpreting.
a: Int = 10
b: Any = (1,hi)
Note that even though the predicate a == 5
will never be true
and thus the consequent branch will never be taken, the typer does not take that into account.请注意,即使谓词
a == 5
永远不会为true
,因此永远不会采用后续分支,但打字机不会考虑这一点。
Note also that if you had a method with that body:另请注意,如果您有一个包含该主体的方法:
def someMethod = {
val a = 10
val b = if(a==5) println("hello") else (1,"hi")
}
The result type of that method would be Unit
, because the result type is the type of the last expression in the method and an assignment (being a side-effect) has the type Unit
.该方法的结果类型将是
Unit
,因为结果类型是该方法中最后一个表达式的类型,并且赋值(作为副作用)具有类型Unit
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.