【问题标题】:Ternary operator in an anonymous function [duplicate]匿名函数中的三元运算符[重复]
【发布时间】:2018-09-26 01:11:15
【问题描述】:

在 Scala 中我可以做到:

scala> (1 to 5).map( x => if (x % 2 == 0) x else "Not even number" )
res58: scala.collection.immutable.IndexedSeq[Any] = Vector(Not even number, 2, Not even number, 4, Not even number)

但我做不到:

(1 to 5).map( x => (x % 2 == 0) ? x : "Not even number" )

我明白了:

<console>:1: error: identifier expected but string literal found.

有什么想法吗?

【问题讨论】:

    标签: scala


    【解决方案1】:

    Scala 中没有三元 ? 运算符,使用 if/else 是实现此目的的唯一方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      • 2012-10-14
      • 2016-11-21
      • 2012-10-15
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多