简体   繁体   中英

Scala, can I pass a class constructor parameter (not defined as implicit) as an implicit value?

I'm new to Scala so bear with me.

class NeedsImplicitSuffix(prefix: String)(implicit suffix: String) {
    def doImplicitly(): String = {
        s"$prefix-$suffix"
    }
}

class HasPrefixInConstructor(suffix: String) {
    def thisWontCompile(): NeedsImplicitSuffix = {
        new NeedsImplicitSuffix("that")
    }
}

If I try this in the console (or IDE) I get the following error.

error: could not find implicit value for parameter suffix: String

Within the context of the method thisWontCompile can I access the string suffix and make it possible to pass as an implicit value? I recognize that the canonical way of doing this in Scala would be to redefine the "HasPrefixInConstructor" class definition, but that severely messes with constraints that I have on instantiation. I'm hoping that my hands aren't tied here.

Yes, you can pass implicit parameter explicitly

class HasPrefixInConstructor(suffix: String) {
    def thisWontCompile(): NeedsImplicitSuffix = {
        new NeedsImplicitSuffix("that")(suffix) // suffix is passed explicitly 
    }
}

Scala REPL

scala> case class A(a: Int)(implicit b: String)
defined class A

scala> class B(b: String) {
     | def foo: A = A(1)(b)
     | }
defined class B

scala>

An alternative to @pamu's answer: you can also just declare

implicit val suffix1: String = suffix

in any scope: class scope, method scope, a block. Which of these approaches is better will depend on specifics of your situation.

As an additional note, having implicits of simple types like Int or String is discouraged: it's far too easy to end up with conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM