将类型模式匹配转换为类型类 [英] Convert type pattern maching to type class

查看:72
本文介绍了将类型模式匹配转换为类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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)
}

如何将其转换为使用类型类?

How can I convert it to use type class?

有人问我数组的类型是什么.情况很复杂.数组声明如下:

I was asked what the type of the array is. It's complicated. The array is declared like that:

val array = obj.asInstanceOf[mutable.WrappedArray[Any]].array

obj是函数接受的参数:

obj is a parameter that the function accepts:

val createBuffer = (obj: Any, dType: DataType) => dType match {

该函数在这里调用:

val byteBuffer: Option[ByteBuffer] = createBuffer(row.get(i), types(i))

行是Spark DataFrame行.

row is a Spark DataFrame row.

推荐答案

typeclass 看起来像这样:

trait ByteSize[T] {
  def tSize: Int
}

object ByteSize {
  implicit final val IntByteSize: ByteSize[Int] =
    new ByteSize[Int] {
      override final val tSize: Int = 4
    }

  implicit final val LongByteSize: ByteSize[Long] =
    new ByteSize[Long] {
      override final val tSize: Int = 8
    }

  // Other instances.
}

object syntax {
  object bytes {
    implicit class ArrayOps[T](private val arr: Array[T]) extends AnyVal {
      final def allocateByteBuffer(implicit ev: ByteBuffer[T]): ByteBuffer =
        ByteBuffer.allocate(ev.tSize * array.length)
    }
  }
}

您可以像这样使用:

import syntax.bytes._

val arr: Array[Int] = ???

val byteBuffer = arr.allocateByteBuffer

您甚至可以提供更有用的扩展方法,例如可以直接填充它,而不仅仅是分配 ByteBuffer .

You may even provide more useful extension methods, like instead of just allocating the ByteBuffer, you can fill it directly.

注意,请记住 typclasses 是类型驱动的,因此可以在编译时进行解析. 如果您不知道数组的类型,那么模式匹配就是您所能做的最好的事情.
您可能希望查看是否可以重构代码,以便使其成为更强大的类型,因为通常 Any 被认为是代码异味.但是,如果您不能这样做,或者为了获得收益而花了太多功夫,那么类型类就是工作的错误工具.

Note, remember typclasses are type driven, thus are resolved at compile time. If you do not know the type of your array, then that pattern match is the best you can do.
You may want to see if you can refactor your code so it becomes more strongly types, since Any, in general, is considered a code smell. But, if you can't or it is too much work for the benefits, then typeclasses are simply the wrong tool for the job.

这篇关于将类型模式匹配转换为类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆