有人可以向我解释Scala中的隐式转换吗? [英] Can someone explain me implicit conversions in Scala?

查看:97
本文介绍了有人可以向我解释Scala中的隐式转换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说, BigInt 是否可以将int转换为BigInt?

And more specifically how does the BigInt works for convert int to BigInt?

在源代码中,其内容为:

In the source code it reads:

...
implicit def int2bigInt(i: Int): BigInt = apply(i)
...

该代码如何调用?

我可以理解另一个示例的方式: 日期文字" 有效.

I can understand how this other sample: "Date literals" works.

输入.

val christmas = 24 Dec 2010  

定义:

implicit def dateLiterals(date: Int) = new {
  import java.util.Date  
  def Dec(year: Int) = new Date(year, 11, date)
}

int获取并以int作为参数传递消息Dec时,系统会寻找另一种可以处理请求的方法,在这种情况下为Dec(year:Int)

When int get's passed the message Dec with an int as parameter, the system looks for another method that can handle the request, in this case Dec(year:Int)

Q1.我对Date文字的理解正确吗?

Q1. Am I right in my understanding of Date literals?

Q2.它如何应用于BigInt?

Q2. How does it apply to BigInt?

谢谢

推荐答案

当提供的类型与预期的类型不匹配时,Scala编译器会在范围内标记为隐式的任何方法将提供的类型作为参数,并返回结果是预期的类型.如果找到,它将在两者之间插入对方法的调用. 在BigInt情况下,假设您有一个方法

When a the provided type doesn't match the expected type, the Scala compiler looks for any method in scope marked implicit that takes the provided type as parameter and returns the expected type as a result. If found, it inserts the call to the method in between. In the BigInt case, say you have a method

doSomethingWithBigInt(d:BigInt)=....

然后用整数调用它:

doSomethingWithBigInt(10)

由于类型不匹配,Scala编译器将生成:

As the types don't match, the Scala compiler will generate:

doSomethingWithBigInt(int2bigInt(10))

假定隐式int2bigInt在范围内

Assuming the implicit int2bigInt is in scope

这篇关于有人可以向我解释Scala中的隐式转换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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