代码之家  ›  专栏  ›  技术社区  ›  stack0114106

scala如何在匿名函数中模拟三元运算符

  •  -7
  • stack0114106  · 技术社区  · 6 年前

    我想通过模拟三元运算符在下面的代码中得到“ae”,但得到下面的错误

    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>
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Dmytro Mitin    6 年前

    有效的Scala语法是

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

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

    是Java语法。