【问题标题】:scala how to mimic a ternary operator in anonymous functionsscala如何在匿名函数中模仿三元运算符
【发布时间】:2019-02-06 09:58:59
【问题描述】:

我想通过尝试模仿三元运算符在下面的代码中得到“a    e”,但得到以下错误

scala> val ab="apple"
ab: String = apple

scala> ab.toCharArray.map( x => "aeiou".indexOf(x) >= 0  )
res99: Array[Boolean] = Array(true, false, false, false, true)

scala> ab.toCharArray.map( x => "aeiou".indexOf(x) >= 0 ? x : ' ' )
<console>:1: error: identifier expected but character literal found.
ab.toCharArray.map( x => "aeiou".indexOf(x) >= 0 ? x : ' ' )
                                                       ^

scala>

【问题讨论】:

标签: scala


【解决方案1】:

有效的 Scala 语法是

ab.toCharArray.map(x => if ("aeiou".indexOf(x) >= 0) x else ' ')

相反

ab.chars().map(x -> "aeiou".indexOf(x) >= 0 ? x : ' ');

是Java语法。

【讨论】:

  • 感谢 Dmytro.. 我对 Java 和 scala 语法感到困惑.. 它可以工作。
猜你喜欢
  • 2018-09-26
  • 1970-01-01
  • 2012-10-14
  • 2017-03-31
  • 2021-09-30
  • 1970-01-01
  • 2013-06-07
  • 2022-01-04
  • 1970-01-01
相关资源
最近更新 更多