5

DSL を開発するとき、暗黙的な変数のスコープを制限し、同時にそのような暗黙的な変数が定義されているという事実を隠す最もクリーンな方法は何ですか?

例として、これは望ましい動作です...

object External
{
    def funNeedingValue(implicit a : String)
    {
        println(a)
    }
}

object Main extends App
{
    useValue("Hi") {
        // Implicit string "Hi" is only defined in this block
        External.funNeedingValue // Prints "Hi"
    }

    External.funNeedingValue // Compilation error: No implicit String defined
}

以下は近いですが、必要なプロパティのすべてを持っているわけではありません...

// The following works, but does not hide the fact that there is an implicit  
// variable defined.

object Main extends App
{
    {
        implicit val implicitValue = "Hi"
        External.funNeedingValue // Prints "Hi"
    }

    External.funNeedingValue // Compilation error: No implicit String defined
}

// The following hides that there is an implicit variable defined, but breaks
// the scoping requirement and destroys thread safety.

abstract class Parent
{
    implicit var implicitValue = ""

    def useValue(valueToMakeImplicit : String)(f : => Unit)
    {
        implicitValue = valueToMakeImplicit
        f()
    }
}

class Child extends Parent
{
    def go()
    {
        useValue("Hi") {
            External.funNeedingValue // Prints "Hi"
        }

        External.funNeedingValue // Scoping issue: also prints "Hi"
    }
}

object Main extends App
{
    new Child().go()
}

// The following works, but is harder to read and still doesn't really
// hide the implicit value

object Main extends App
{
    def useValue(valueToMakeImplicit : String)(f : String => Unit)
    {
        f(valueToMakeImplicit)
    }

    useValue("Hi") { 
        implicit value : String => {
            External.funNeedingValue // Prints "Hi"
        }
    }

    External.funNeedingValue // Compilation error: No implicit String defined
}
4

1 に答える 1

1

変換するマクロを作成できます

useValue("Hi") {
    // Implicit string "Hi" is only defined in this block
    External.funNeedingValue // Prints "Hi"
}

の中へ

{
  implicit val iString: String = "Hi"
  External.funNeedingValue
}

マクロなしで最後の例よりもうまくいくとは思いません。

于 2014-04-21T05:18:09.163 に答える