How do I map an implicit class parameter to a variable to a variable?

I am facing an interesting problem with implicit parameters and tratis.

I have an abstract class Parent

that takes one integer and two other parameters implicitly:

abstract class Parent(a: Int)(implicit str: String, map: Map[String,String]) {/*...*/}

      

and a trait ClassTrait

to be mixed with Parent

and uses implicits:

trait ClassTrait {
    val str: String
    val map: Map[String,String]

    def doSth() = str.length
}

      

so now I want to do it like this ( withnout keyword abstract

):

class Child(a: Int)(implicit str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
    def doSth2 = doSth * 10
}

      

What syntax should I use to map implicit parameters to define vals ? The compiler returns this error:

foo.scala:10: error: class Child needs to be abstract, since:
value map in trait ClassTrait of type Map[String,String] is not defined
value str in trait ClassTrait of type String is not defined
class Child(a: Int)(implicit str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
      ^
one error found

      

In a complex example, I am using implicit parameters in a trait, but since traits cannot have any parameters (do not have a constructor), I need to declare the implications used again.

Thanks for the help.

+3


source to share


2 answers


Try

class Child(a: Int)(implicit val str: String, map: Map[String,String]) extends Parent(a) with ClassTrait {
   def doSth2 = doSth * 10
 }

      

(see val

i added)



Or use case class

. Then they will be fields.

An alternative way might be to not make them implicit and use the apply method on a companion object that accepts implications to set them. But you still need to make them fields, your current code technically just treats them as args constructors.

+3


source


You can promote your class parameters in fields using the val keyword:

abstract class Parent(a: Int)(implicit val str: String, val map: Map[String,String]) {/*...*/}

      



Note the "val str" and "val map" instead of "str" ​​and "map". This way, they will be correct read-only members and provide the implementation of the abstract members of your trait.

+2


source







All Articles