尝试一下:@loginForm("email").getClass()@loginForm("email").value.getClass()在Login.scala.html和loginform.scala.html上都进行此更改,您会发现在每种情况下您都处理不同的类.当您浏览loginform模板时,您的field.value将被包装在scala.Some对象中,这就是.getOrElse在这种情况下进行编译的原因.在主视图中直接执行此操作时,您永远不会离开Java-class-world,因此您的field.value将直接作为String返回.如果您使用的是最新版本的Play,则应该可以使用Field.valueOr方法而不是getOrElse.@loginForm("email").valueOr("xyz")I have the following template code:views/Login.scala.html:@(loginForm: Form[views.Data])@import mytemplates.loginform@Main("") { email:@loginform(loginForm("email")) @*email:@loginForm("email").value.getOrElse("xyz")*@}views/mytemplates/loginform.scala.html:@(emailField: Field)@emailField.value.getOrElse("xyz")views/Main.scala.html:@(page: String)(content: Html)<!DOCTYPE html><html> <body> @content</html>views/Data.java:package views;import play.data.validation.ValidationError;import java.util.List;public class Data { public String email = ""; public Data() { } public List<ValidationError> validate() { return null; }}Compiling the above is successful. But if line @*email:@loginForm("email").value.getOrElse("xyz")*@ in Login.scala.html is uncommented compiling produces an value getOrElse is not a member of String error.Why does this happen? I'd like to exclude the template mytemplates.loginform but can't get it to work.edit: Following estmatic's advice I get the following:views/Login.scala.html:@loginForm("email").getClass: class play.data.Form$Field@loginForm("email").valueOr("").getClass: class java.lang.Stringviews/mytemplates/loginform.scala.html:@emailField.getClass: class [email protected]: class scala.None$I had to use valueOr("") in Login.scala.html otherwise a NullPointer execution exception would be produced. Clearly they are all different classes. I haven't used Play framework much and am not sure what this means. 解决方案 Since it looks like you have a Java project, the framework is going to do some automatic conversions here and there between the Java classes and their Scala equivalent.Try this out:@loginForm("email").getClass()@loginForm("email").value.getClass()Make this change on both Login.scala.html and loginform.scala.html and you'll see that you are dealing with different classes in each scenario.When you go through the loginform template your field.value will be wrapped in a scala.Some object, which is why .getOrElse compiles in that case. When you do it directly in the main view you never leave Java-class-world, so your field.value is returned directly as a String.If you are using the latest version of Play then you should be able to use the Field.valueOr method instead of getOrElse.@loginForm("email").valueOr("xyz") 这篇关于“值getOrElse不是String的成员"在模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-23 22:35