Scala:强制 A 不是 B 的子类型

2023-11-22

我试图根据参数是否扩展给定的类来重载方法,并且遇到了一些麻烦。使用迈尔斯·萨宾 (Miles Sabin) 的方法,我生成了以下代码:

object ExtendedGenericTypes {

  trait <:!<[A, B] // Encoding for "A is not a subtype of B"

  // Use ambiguity to rule out the cases we're trying to exclude
  implicit def nsubAmbig1[A, B >: A]: A <:!< B = null
  implicit def nsubAmbig2[A, B >: A]: A <:!< B = null

  // The implicit substitutions
  implicit def nsub[A, B]: A <:!< B = null
}

我的用例:

import ExtendedGenericTypes._

class Foo

def foobar[T](x: T)(implicit ev: T <:< Foo) = "hello"
def foobar[T](x: T)(implicit ev: T <:!< Foo) = 5

println(foobar(new Foo()))

不幸的是,这会导致歧义,编译器不知道要调用这两个方法中的哪一个。我正在寻找关于为什么在这种情况下存在歧义的解释(与迈尔斯要点中概述的其他更简单的情况相反)以及如何规避这个障碍。请注意,我需要在参数级别执行此检查(而不是定义一个方法并在主体中执行检查),因为我想要具有不同的返回类型。


第一个问题是由于您在 REPL 中的工作方式,第二个问题是foobar只是掩盖了第一个。如果您想要重载定义,则需要使用:paste同时定义两者。

这仍然不会让你得到你想要的,只是一个新的错误消息:

scala> println(foobar(new Foo))
<console>:14: error: ambiguous reference to overloaded definition,
both method foobar of type [T](x: T)(implicit ev: EGT.<:!<[T,Foo])Int
and  method foobar of type [T](x: T)(implicit ev: <:<[T,Foo])String
match argument types (Foo) and expected result type Any
              println(foobar(new Foo))
                      ^

(注意我已经缩写了ExtendedGenericTypes因为我讨厌水平滚动条。)

您甚至可以尝试提供<:<明确实例:

scala> foobar(new Foo)(implicitly[Foo <:< Foo])
<console>:14: error: ambiguous reference to overloaded definition,
both method foobar of type [T](x: T)(implicit ev: EGT.<:!<[T,Foo])Int
and  method foobar of type [T](x: T)(implicit ev: <:<[T,Foo])String
match argument types (Foo)
              foobar(new Foo)(implicitly[Foo <:< Foo])
              ^

所以这里发生的事情是编译器不会让第二个参数列表确定要使用哪个重载定义。这似乎意味着具有多个参数列表且第一个参数列表相同的重载方法本质上是无用的。可能有一张票——乍一看我能想到的最接近的是SI-2383.

不过,这些都不重要,因为您不应该在这里使用重载方法——重载是一个可怕的“功能”,是 Java 和 Java 的后遗症。破坏各种东西.

不过,还有其他可能的方法。我最喜欢的一些奇怪的 Scala 技巧依赖于这样一个事实:您可以为隐式参数提供默认值,如果编译器找不到实例,将使用该默认值。如果我理解正确的话,你想要这样的东西:

class Foo

def foobar[T](x: T)(implicit ev: T <:< Foo = null) =
  Option(ev).fold[Either[Int, String]](Left(5))(_ => Right("hello"))

case class Bar(i: Int) extends Foo
case class Baz(i: Int)

进而:

scala> foobar(Bar(13))
res0: Either[Int,String] = Right(hello)

scala> foobar(Baz(13))
res1: Either[Int,String] = Left(5)

请注意,我正在使用Either而不是让隐式的存在决定返回类型。有一些方法可以实现这一点(比如无形的's 第一类多态函数值),但在这种情况下他们可能有点矫枉过正了。


更新:好的,既然你要求了:

import shapeless._

trait LowPriorityFoobar { this: Poly1 =>
  implicit def anyOld[T] = at[T](_ => 5)
}

object foobar extends Poly1 with LowPriorityFoobar {
  implicit def foo[T](implicit ev: T <:< Foo) = at[T](_ => "hello")
}

进而:

scala> foobar(Bar(13))
res6: String = hello

scala> foobar(Baz(13))
res7: Int = 5

没有包装纸。不过,在采取这种方法之前,您应该认真考虑一下。


更新到更新,为了完整性:您也可以更直接地(但也更详细地)执行此操作,而无需使用依赖方法类型的 Shapeless(同样,您需要使用:paste一次定义所有这些):

class Foo

trait IsFooMapper[I] {
  type Out
  def apply(i: I): Out
}

trait LowPriorityIsFooMapper {
  implicit def isntFoo[A] = new IsFooMapper[A] {
    type Out = Int
    def apply(a: A) = 5
  }
}

object IsFooMapper extends LowPriorityIsFooMapper {
  implicit def isFoo[A](implicit ev: A <:< Foo) = new IsFooMapper[A] {
    type Out = String
    def apply(a: A) = "hello"
  }
}

def foobar[A](a: A)(implicit ifm: IsFooMapper[A]) = ifm(a)

进而:

scala> foobar(Bar(13))
res0: String = hello

scala> foobar(Baz(13))
res1: Int = 5

再次强调,这是相当高级的东西,应该谨慎使用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Scala:强制 A 不是 B 的子类型 的相关文章

随机推荐