加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy多行String有什么问题?

发布时间:2020-12-14 16:40:34 所属栏目:大数据 来源:网络整理
导读:Groovy脚本引发一个错误: def a = "test" + "test" + "test" 错误: No signature of method: java.lang.String.positive() is applicable for argument types: () values: [] 虽然这个脚本工作正常: def a = new String( "test" + "test" + "test") 为什
Groovy脚本引发一个错误:

def a = "test"
  + "test"
  + "test"

错误:

No signature of method: java.lang.String.positive() is 
applicable for argument types: () values: []

虽然这个脚本工作正常:

def a = new String(
  "test"
  + "test"
  + "test"
)

为什么?

解决方法

由于groovy没有EOL标记(如;),如果你把运算符放在下面的行,它会感到困惑

这将工作而不是:

def a = "test" +
  "test" +
  "test"

因为Groovy解析器知道在下面一行中期望的东西

Groovy将你的原始def视为三个单独的语句。第一个分配测试给a,第二个尝试使“测试”为正(这是它失败的地方)

使用新的String构造方法,Groovy解析器仍然在构造函数中(因为大括号尚未关闭),因此它可以将三行合并成一个语句

对于真正的多行字符串,您还可以使用三重引号:

def a = """test
test
test"""

将创建一个字符串与测试三行

此外,你可以使它更整洁:

def a = """test
          |test
          |test""".stripMargin()

stripMargin method将从每一行向左修剪(直到并包括| char)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读