gpt4 book ai didi

scala - 隐式使用结构类型

转载 作者:行者123 更新时间:2023-12-02 04:58:02 25 4
gpt4 key购买 nike

使用简单类型的隐式值有什么方便的方法?理想情况下,我想做这样的事情:

scala> :paste
// Entering paste mode (ctrl-D to finish)

type A = String
type B = String
implicit val a: A = "a"
implicit val b: B = "b"
def c(implicit ab: A) = println(ab)

// Exiting paste mode, now interpreting.

defined type alias A
defined type alias B
a: A = a
b: B = b
c: (implicit ab: A)Unit

scala> c
<console>:13: error: ambiguous implicit values:
both value a in object $iw of type => A
and value b in object $iw of type => B
match expected type A

也不能像 String 或 Long 那样子类化 final case 类

scala> class C extends String
<console>:11: error: illegal inheritance from final class String
class C extends String

最佳答案

虽然 Tim 是正确的,但他的方法会在字符串周围创建一个包装器,从而引入运行时开销。我们可以让编译器完成所有这一切,而无需使用称为类型标记的技术创建新对象。以下代码无耻地取自 shapeless来源:

trait Tagged[U] 
type @@[+T, U] = T with Tagged[U]

class Tagger[U] {
def apply[T](t : T) : T @@ U = t.asInstanceOf[T @@ U]
}

def tag[U] = new Tagger[U]

使用这些定义,您可以编写以下内容:

trait A
trait B

implicit def a: String @@ A = tag[A]("foo")
implicit def b: String @@ B = tag[B]("bar")

def foo(implicit a: String @@ A) = a.toString
def bar(implicit b: String @@ B) = b.toString

scala> foo
res21: String = foo

scala> bar
res22: String = bar

关于scala - 隐式使用结构类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com