[英]Weird situation with Scala Play - type inference
@(css: Option[String])(content: Html)(customJS: Option[Array[String]])
@for(js <- customJS if !customJS.isEmpty) {
<script src="@routes.Assets.at(js)"></script>
}
I was writing for this small for-comprehension that will loop through and print out the uri String. 我正在为这个小的理解而写,它将遍历并打印出uri字符串。 Since it is possible to be none, or an array of Strings, I used
Option
. 由于可能为无,也可能为字符串数组,因此我使用了
Option
。
Then the complier from typesafe activator told me that @routes.Assets.at()
is supposed to take a String
not an Array[String]
. 然后,来自类型安全激活器的编译器告诉我
@routes.Assets.at()
应该采用String
而不是Array[String]
。 I'm in shock because js is supposed to be String
right? 我很震惊,因为js应该是
String
吧?
Then I tried to write like this: 然后我尝试这样写:
@for(js <- customJS if !customJS.isEmpty) {
@var uri = js
<script src="@routes.Assets.at(js)"></script>
}
Then the complier said that added line is illegal start of "simple expression". 然后,编译器说添加的行是“简单表达式”的非法开头。
It is not a simple expression! 这不是一个简单的表达! It is a full for-comprehension with
{}
! 对
{}
完全理解! Also I was eventually forced to use js.asInstanceOf[String]
to fool the complier. 同样,我最终也被迫使用
js.asInstanceOf[String]
欺骗编译器。 I'm not glad with this because once I was told that I should never use asInstanceOf
. 我对此
asInstanceOf
,因为一旦被告知我永远不要使用asInstanceOf
。 So what's wrong with my original code? 那么我的原始代码怎么了?
Note that you should not use Array
- use Seq
. 请注意,您不应使用
Array
-use Seq
。
There is no need in Option[Seq[String]]
- use Seq[String]
. 在
Option[Seq[String]]
不需要-使用Seq[String]
。 Instead of None
you could always use an empty Seq
. 可以使用空的
Seq
代替None
。
In case you still want to use Option[Seq[String]]
you should rewrite your for
like this: 如果您仍然想使用
Option[Seq[String]]
,则应该这样重写您for
:
@for(jsArray <- customJS; js <- jsArray) {
<script src="@routes.Assets.at(js)"></script>
}
You don't need if !customJS.isEmpty
. 您不需要
if !customJS.isEmpty
。 Option
is something like collection with 1 or 0 elements. Option
类似于具有1或0个元素的集合。 Element of Option[Array[String]]
is Array[String]
. Option[Array[String]]
元素是Array[String]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.