限制 Scala 参数中的特定类型? [英] Restrict specific type in Scala paramaters?

查看:35
本文介绍了限制 Scala 参数中的特定类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我会遇到一种情况,我特别想限制可以发送到函数的内容,但几乎可以接受任何其他类型.这在 Scala 中可能吗?例如,此代码在运行时处理我的问题 - 接受除 Option 对象之外的任何类型 T.编译器能捕获它吗?谢谢

Sometimes I come across a situation where I specifically want to restrict what can be sent to the function, but accept almost any other kind. Is this possible in Scala? For example, this code deals with my issue at runtime - accepting any type T except Option objects. Could the compiler catch it? Thank you

def apply[T:TypeTag](t: T): TaggedOption[T] =
  t match {
    case o: Option[_] =>
      // ensure this can't be created
      throw new Exception("This function doesn't work with Options")
    case other =>
      TaggedOption_(Some(t), PowerTag[T])
  }

推荐答案

可以限制类型参数:

scala> trait <:!<[A, B]
defined trait $less$colon$bang$less

scala> implicit def nsub[A, B] : A <:!< B = null
nsub: [A, B]=> <:!<[A,B]

scala> implicit def nsubAmbig1[A, B >: A] : A <:!< B = ???
nsubAmbig1: [A, B >: A]=> <:!<[A,B]

scala> implicit def nsubAmbig2[A, B >: A] : A <:!< B = ???
nsubAmbig2: [A, B >: A]=> <:!<[A,B]

scala> def notOption[A](a: A)(implicit ev: A <:!< Option[_]) = a
notOption: [A](a: A)(implicit ev: <:!<[A,Option[_]])A

scala> notOption(1)
res0: Int = 1

scala> notOption(List(""))
res1: List[String] = List("")

scala> notOption(Option(1))
<console>:14: error: ambiguous implicit values:
 both method nsubAmbig1 of type [A, B >: A]=> <:!<[A,B]
 and method nsubAmbig2 of type [A, B >: A]=> <:!<[A,B]
 match expected type <:!<[Option[Int],Option[_]]
              notOption(Option(1))
                       ^

scala> notOption(Some(1))
<console>:14: error: ambiguous implicit values:
 both method nsubAmbig1 of type [A, B >: A]=> <:!<[A,B]
 and method nsubAmbig2 of type [A, B >: A]=> <:!<[A,B]
 match expected type <:!<[Some[Int],Option[_]]
              notOption(Some(1))
                       ^

scala> notOption(None)
<console>:14: error: ambiguous implicit values:
 both method nsubAmbig1 of type [A, B >: A]=> <:!<[A,B]
 and method nsubAmbig2 of type [A, B >: A]=> <:!<[A,B]
 match expected type <:!<[None.type,Option[_]]
              notOption(None)
                       ^

隐式使 Option 的情况变得模棱两可.有关代码应该如何工作的更详细说明,请参阅以下 scala-user 上的线程.

The implicits make the Option case ambiguous. For a more detailed explanation on how the code is supposed to work, see the following thread on scala-user.

这篇关于限制 Scala 参数中的特定类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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