Scala委托导入隐式转换 [英] Scala delegate import of implicit conversions

查看:232
本文介绍了Scala委托导入隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中,我如何将隐式转换导入我的范围,这样我就不必有一个大的环境类,它提供了库函数/值(对于我正在创建的DSL)作为简单来说,我可以从对象移动隐式转换,并在写入时仍然导入:



导入MyDslEnvironment ._





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



PS:在任何人煽动我之前 - 是的,我知道可能来自隐含转换的陷阱和肮脏。

解决方案

我的倾向是将含义放在一个包装对象中。



假设你的工作将在包com.acme.my中定义dsl。您的源文件安排在目录层次结构com> acme> mydsl中。在目录mydsl中,定义一个如下所示的对象:

  package com.acme; //我们在mydsl目录中,但是在


包对象mydsl {

中隐藏没有mydsl
//隐式def idioticallyStringsAre5(s:字符串):Int = 5

//定义应在
内可用的其他实用程序//包或可导入

}

现在,您可以这样做:

  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

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



我真的很喜欢包对象。在Java中总是看起来很有趣,只能为实现函数使静态成员的类充满。包对象作为这些实用程序的非常优雅的名称空间,包括隐式转换。


In Scala, how can I delegate the importing of implicit conversions into my scope, such that I don't have to have a big "environment" class which provides both library functions/values (for a DSL I am creating) as well as implicit conversions?

In short, can I move my implicit conversions from an object, and still have it imported when I write:

import MyDslEnvironment._

?

The goal of this is to make the importing and use of my framework simple and lightweight, in the sense that only a single import statement gives the user the needed functionality of my DSL/framework.

PS: Before anyone flames me - yes, I am aware of pitfalls and nastiness that can come from implicit conversions.

解决方案

My inclination would be to put the implicits in a package object.

Suppose that your work will be defined in the package com.acme.mydsl. Your source files are arranged in a directory hierarchy com > acme > mydsl. In the directory mydsl, define an object like so:

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

}

Now, you can do this:

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

By importing import com.acme.mydsl._, you got all the package-level function definitions, including the implicit conversion.

I really like package objects. It always seemed hokey in Java to have to make classes full of static members just for utility functions. Package objects serve as very elegant name spaces for these utilities, including implicit conversions.

这篇关于Scala委托导入隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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