简体   繁体   中英

scala class constructor implicit paramaters are fields?

Do implicit parameters in a class constructor behave like regular parameters in a way that if they are referenced somewhere inside that class they automatically become fields ?

If so how to avoid that in this case:

class Triangle[@specialized T, V[_]](p1:V[T],p2:V[T],p3:V[T])(implicit ev: Addable[V[T]]){
   def someFuncThatUsesAddable(): Any = ???
}

If I need to create a lot of those triangles, each instance will contain reference to Addable resulting in increased memory use.

Interesting question. I didn't know and I decided to check. I see a field is created for each implicit parameter:

import scala.reflect.runtime.{universe => ru}
class X
class A()
class B(val i: Int)
class C(val i: Int)(implicit x: X)

object Xc extends App {
  implicit val x = new X()

  def getTypeTag[T: ru.TypeTag](obj: T) = ru.typeTag[T]

  def allDecls(d: ru.MemberScope) = d.mkString("[", ",", "]")

  def printTypeInfo(typeA: ru.Type) =
      println(s"type ${typeA.typeSymbol} has ${typeA.members.size} 
               members. Declarations: " + allDecls(typeA.decls))

      printTypeInfo(getTypeTag(new A()).tpe)
      printTypeInfo(getTypeTag(new B(1)).tpe)
      printTypeInfo(getTypeTag(new C(1)).tpe)
  } 
}

The output:

type class A has 22 members. Declarations: [def <init>: <?>]
type class B has 24 members. Declarations: [val i: <?>,private[this] val i: <?>,def <init>: <?>]
type class C has 25 members. Declarations: [val i: <?>,private[this] val i: <?>,implicit private[this] val x: <?>,def <init>: <?>]

Yes, of course, there would be no other way to do it (as @puhlen pointed out). As an alternative, you could move ev to methods which use it:

class Triangle[@specialized T, V[_]](p1:V[T],p2:V[T],p3:V[T]) {
   def someFuncThatUsesAddable(implicit ev: Addable[V[T]]): Any = ???
}

but note that this changes semantics: it requires that the Addable be in scope at method call site, not when you create the triangle.

As a side note, I wouldn't expect @specialized to be helpful at all when T by itself isn't used anywhere.

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