【问题标题】:Scala pattern matching for typeScala 模式匹配类型
【发布时间】:2020-08-09 02:44:17
【问题描述】:

我写了以下代码:

array(0).getClass match {
  case Int.getClass =>
    byeBuffer = ByteBuffer.allocate(4 * array.length)

  case Long.getClass =>
    ByteBuffer.allocate(8 * array.length)

  case Float.getClass =>
    ByteBuffer.allocate(4 * array.length)

  case Double.getClass =>
    ByteBuffer.allocate(8 * array.length)

  case Boolean.getClass =>
    ByteBuffer.allocate(1 * array.length)

不过,过度使用getClass 让我觉得很笨拙。

有没有更好的写法?

【问题讨论】:

    标签: scala functional-programming pattern-matching


    【解决方案1】:

    您可以省略 getClass 并使用类型运算符 (:):

    val byteBuffer = array(0) match {
      case _: Int =>
        ByteBuffer.allocate(4 * array.length)
      case _: Long =>
        ByteBuffer.allocate(8 * array.length)
      case _: Float =>
        ByteBuffer.allocate(4 * array.length)
      case _: Double =>
        ByteBuffer.allocate(8 * array.length)
      case _: Boolean =>
        ByteBuffer.allocate(1 * array.length)
    }
    

    还要注意,match 是 Scala 中的表达式,因此您可以将 byteBuffer 移到外面并将结果分配给它。这种函数式方法将使其更简洁,并允许我们避免重新分配给var,而是使用val

    如果您想使用与类型匹配的变量,则可以简单地编写例如 l: Long 并使用名称为 Long 的变量 l

    【讨论】:

    • array.getClass.getComponentType。如果数组为空等
    • 或者甚至更好地使用 typeclass,因为匹配类型 (实际上是类) 并不详尽,而且 Amy 无法匹配复杂类型。跨度>
    • 非常感谢 cmets。当然,我同意在简单版本和类型类中检查空虚。但是使用typeclasses虽然很优雅干净,但就是要完全重写代码,不知道OP是否想深入更复杂的话题(模式匹配比较容易)
    • 我真的很想把它转换成一个类型类。您能否在答案中添加一个带有类型类的版本?
    • 我为此提出了一个新问题:stackoverflow.com/questions/61443874/…
    猜你喜欢
    • 2013-03-17
    • 2019-04-20
    • 2014-03-05
    • 2013-12-01
    • 1970-01-01
    • 2018-01-03
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多