Scala中的隐式函数。这是怎么回事?
我正在学习Scala的教程,我看到了以下内容:Scala中的隐式函数。这是怎么回事?,scala,Scala,我正在学习Scala的教程,我看到了以下内容: object implicitFunctions extends App { println("Step 1: How to create a wrapper String class which will extend the String type") class DonutString(s: String) { def isFavoriteDonut: Boolean = s == "Glazed Donut"
object implicitFunctions extends App {
println("Step 1: How to create a wrapper String class which will extend the String type")
class DonutString(s: String) {
def isFavoriteDonut: Boolean = s == "Glazed Donut"
}
println("\nStep 2: How to create an implicit function to convert a String to the wrapper String class")
object DonutConversions {
implicit def stringToDonutString(s: String) = new DonutString(s)
}
println("\nStep 3: How to import the String conversion so that it is in scope")
import DonutConversions._
println("\nStep 4: How to create String values")
val glazedDonut = "Glazed Donut"
val vanillaDonut = "Vanilla Donut"
println("\nStep 5: How to access the custom String function called isFavaoriteDonut")
println(s"Is Glazed Donut my favorite Donut = ${glazedDonut.isFavoriteDonut}")
println(s"Is Vanilla Donut my favorite Donut = ${vanillaDonut.isFavoriteDonut}")
}
到底发生了什么?我想在String
类上找不到任何方法,因此我们查看导入的隐式,并通过调用函数并传入缺少的方法(字符串)的接收者,从String
进行转换。是这样吗
为什么隐式函数必须被包装在对象中?它被包装在一个DonutString中,这样你就可以调用DonutString方法,比如isFavoriteDonut
${glazedDonut.isFavoriteDonut}"
调用上述函数时,编译器在字符串中搜索isFavoriteDonut
方法(因为glazedDonut
是字符串类型)。当然,它没有找到它
因此,编译器然后搜索一个隐式,它可以将字符串
转换为其他类型(我们称之为未知
),这样这个未知
类型包含isFavoriteDonut
方法
它在作用域中找到这样一个隐式函数,它可以转换String=>DonutString
,它知道DonutString
包含glazedDonut
为什么隐式对象必须包装在对象中
规范不允许创建顶级隐式类和函数
隐式修改器对于所有类型成员以及顶级对象都是非法的
您好,Jatin,如果我们有多个具有不同名称但输入类型(参数)相同的隐式函数,编译器会说歧义问题吗?是的。这会引起错误