Can I simulate Scala SIP-18-syle import?

Scala SIP 18 provides a way to force users to provide an import statement to use certain advanced or insecure language features. For example, to use higher type types , you need

import scala.language.higherKinds

or you will get a compiler warning indicating that you are using an advanced function.

Is there a way to reproduce or reproduce this behavior in my own library? For example, I can:

trait MongoRepository[E <: Entity] {
  val casbahCollection: com.mongodb.casbah.MongoCollection
}

I published a publication casbahCollectionto reveal the basic collection to the user if necessary. But this is really not what I want my users to do this because it was an impenetrable abstraction. So I want to get them to do something like this:

import my.library.mongo.leakyAbstraction

Before doing something like this:

widgetRepo.casbahCollection.find()

Is it possible? Is there a way I could suggest this behavior is a little more effective than just posting a big ugly warning in the docs?

+4
source share
1 answer

You can fake it with an implicit, similar to how it Await.resultworks in scala.concurrent.

First create sealed traitone that represents “permission” for direct access to your DAO:

@implicitNotFound("Import my.library.mongo.leakyAbstraction to directly access Mongo")
sealed trait CanAccessMongo

And then the object that extends it:

implicit object leakyAbstraction extends CanAccessMongo

. CanAccessMongo , .

MongoRepository cashbahCollection ( val def). , val, , .

def cashbahCollection(implicit permit: CanAccessMongo) = ...

leakyAbstraction , . , , implicitNotFound.

, leakyAbstraction .

+8

All Articles