gpt4 book ai didi

Scala 委托(delegate)导入隐式转换

转载 作者:行者123 更新时间:2023-12-01 10:59:06 28 4
gpt4 key购买 nike

在 Scala 中,我如何将隐式转换的导入委托(delegate)到我的范围中,这样我就不必拥有一个提供库函数/值(对于我正在创建的 DSL)的大“环境”类以及隐式转换?

简而言之,我能否将我的隐式转换从一个对象中移出,并在我编写时仍然导入它:

导入 MyDslEnvironment._

?

这样做的目的是使我的框架的导入和使用变得简单和轻量级,因为只有一个导入语句才能为用户提供我的 DSL/框架所需的功能。

PS:在有人抨击我之前 - 是的,我知道隐式转换可能带来的陷阱和麻烦。

最佳答案

我倾向于将隐式函数放在包对象中。

假设您的工作将定义在包 com.acme.mydsl 中。您的源文件排列在目录层次结构 com > acme > mydsl 中。在目录 mydsl 中,像这样定义一个对象:

package com.acme; //we are in the mydsl dir, but note no mydsl in
//in the package declaration

package object mydsl {

implicit def idioticallyStringsAre5( s : String ) : Int = 5

//define other utilities that should be available within
//the package or importable

}

现在,您可以这样做:

scala> import com.acme.mydsl._
import com.acme.mydsl._

scala> def sum( a : Int, b : Int ) = a + b
sum: (a: Int, b: Int)Int

scala> sum("hello", "there")
res0: Int = 10

通过导入 import com.acme.mydsl._,您获得了所有包级函数定义,包括隐式转换。

我真的很喜欢包对象。在 Java 中,必须让类充满静态成员只是为了实用功能,这似乎总是很愚蠢。包对象作为这些实用程序的非常优雅的 namespace ,包括隐式转换。

关于Scala 委托(delegate)导入隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901554/

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