测试是否可以使用隐式转换 [英] Test if implicit conversion is available

查看:75
本文介绍了测试是否可以使用隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图检测是否存在隐式转换,并根据它执行一些代码.例如:

I am trying to detect if an implicit conversion exists, and depending on it, to execute some code. For instance :

if (x can-be-converted-to SomeType)
  return something(conversion(x))
else
  return someotherthing(x)

例如,x是一个Int,应将其转换为RichInt. 在Scala中这可能吗?如果是,怎么办?

For instance, x is an Int and should be converted to a RichInt. Is this possible in Scala? If yes, how?

谢谢

推荐答案

正如其他已经提到的隐式在编译时已解决,因此也许您应该使用类型类来解决此类问题.这样一来,您的优势便是以后可以将功能扩展到其他类型.

As others already mentioned implicits are resolved at compile time so maybe you should rather use type classes to solve problems like this. That way you have the advantage that you can extend functionality to other types later on.

此外,您只需要一个现有的隐式值,而除了默认参数外,就无法直接表示不存在该隐式值.

Also you can just require an existing implicit value but have no way of directly expressing non-existence of an implicit value except for the default arguments.

Jean-Phiippe使用默认参数的解决方案已经相当不错,但是如果您定义一个可以代替隐式参数的单例,则可以省去null.将其设为私有,因为它实际上在其他代码中没有用,甚至可能很危险,因为隐式转换可能会隐式发生.

Jean-Phiippe's solution using a default argument is already quite good but the null could be eliminated if you define a singleton that can be put in place of the implicit parameter. Make it private because it is actually of no use in other code and can even be dangerous as implicit conversions can happen implicitly.

private case object NoConversion extends (Any => Nothing) {
   def apply(x: Any) = sys.error("No conversion")
}

// Just for convenience so NoConversion does not escape the scope.
private def noConversion: Any => Nothing = NoConversion

// and now some convenience methods that can be safely exposed:

def canConvert[A,B]()(implicit f: A => B = noConversion) =
  (f ne NoConversion)

def tryConvert[A,B](a: A)(implicit f: A => B = noConversion): Either[A,B] = 
  if (f eq NoConversion) Left(a) else Right(f(a))

def optConvert[A,B](a: A)(implicit f: A => B = noConversion): Option[B] =
  if (f ne NoConversion) Some(f(a)) else None

这篇关于测试是否可以使用隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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