gpt4 book ai didi

Scala 隐式和类型别名

转载 作者:行者123 更新时间:2023-12-02 03:44:09 26 4
gpt4 key购买 nike

假设我有以下代码:

object Potato extends App {

type CoolString = String
type AwesomeString = String

def potato(string: String)(implicit coolString: CoolString, awesomeString: AwesomeString) = {
s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
}

implicit val ice : CoolString = "Really Cold Ice"
implicit val awe : AwesomeString = "Awe inspiring object"

potato("Stringerino")

}

此代码因问题而失败

[error] ... ambiguous implicit values:
[error] both value ice in object Potato of type => Potato.CoolString
[error] and value awe in object Potato of type => Potato.AwesomeString
[error] match expected type Potato.CoolString
[error] potato("Stringerino")

这样使用隐式是不可能的吗?

最佳答案

Is such use of implicits impossible?

依赖这样一种方法,将像 String 这样的通用类型作为隐式传入,不仅是不可能的,而且是危险的。想想看,范围内的任何 String 实例都将是传递到该方法的合格候选者!

类型别名只是类型别名,仅此而已。对于编译器来说,CoolStringAwesomeString 都只是 String

更好的方法是利用标记类型。例如,这是 tagged type using shapeless :

import shapeless.tag.@@

trait CoolString
trait AwesomeString

type ReallyCoolString = String @@ CoolString
type ReallyAwesomeString = String @@ AwesomeString

然后:

import shapeless.tag

def potato(string: String)(implicit coolString: ReallyCoolString, awesomeString: ReallyAwesomeString) = {
s"$string is a string. Oh, but don't forget - $coolString and also $awesomeString"
}

def main(args: Array[String]): Unit = {
implicit val ice = tag[CoolString][String]("Really Cold Ice")
implicit val awe = tag[AwesomeString][String]("Awe inspiring object")

println(potato("Stringerino"))
}

产量:

Stringerino is a string. 
Oh, but don't forget - Really Cold Ice and also Awe inspiring object

关于Scala 隐式和类型别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47352579/

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