从A隐式转换为Some(a) [英] Implicit conversion from A to Some(a)
问题描述
出于好奇,我想知道是否有可能做类似的事情:
out of curiosity, I was wondering if it was possible to do something like :
def myMethod(
a: Option[A] = None,
b: Option[B] = None,
...
z: Option[Z] = None
): Something = {
...
}
我想要的不是那样称呼的:
What I want is not to have to call it that way:
myMethod(
b = Some(newB),
m = Some(newM)
)
,但是可以只执行myMethod(b = newB, m = newM)
而不必总是将A
转换为Some(a)
.
but instead being able to just do myMethod(b = newB, m = newM)
without having to always convert A
to Some(a)
.
有可能吗?
推荐答案
可能,是的:
object Test {
implicit def anythingToOption[A](a: A): Option[A] = Option(a)
def foo(something: Option[Int]): Unit = ???
def main(args: Array[String]): Unit = {
foo(1)
}
}
您应该这样做吗? 否.为什么?因为具有如此广泛范围的隐式是危险的.首先,当您实际需要范围内的相关隐式变量时,它们可能导致歧义.其次,当某人阅读此内容时,他们将需要查看此转换发生的位置以及原因.第三,这可能会导致细微的错误.
Should you do this? NO. Why? Because implicits with such broad scopes are dangerous. For one, they can lead to ambiguity when you actually need a relevant implicit in scope. Second, when someone reads this, they'll need to see where this conversion happens, and why. Third, this can lead to subtle bugs.
相反,无论您是从Cats库获取扩展方法还是自己编写扩展方法,您都可以使用它们:
Instead, you can use extension methods, whether you get them from the Cats library or write them yourself:
object Test {
implicit class OptionOps[A](val a: A) extends AnyVal {
def toOption: Option[A] = Option(a)
def some: Option[A] = Some(a)
}
def foo(something: Option[Int]): Unit = ???
def main(args: Array[String]): Unit = {
foo(1.toOption)
foo(1.some)
}
}
这篇关于从A隐式转换为Some(a)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!