Import from class instance

Today this would’ve been very handy:

class AClass(arg: String) {
  def f(someOtherArg: String) = ??? // uses arg
  def g() = ??? // uses arg
}

// elsewhere
def someFunc() = {
  import new AClass(myArg)._

  val x = f("foo")
  val y = g()
}

could we have something like this?

Is naming the imported value such a big deal?

1 Like

When you have to reference the name 10+ times in the function it kinda becomes unnecessary noise.

What’s wrong with:

// Start writing your ScalaFiddle code here
class AClass(arg: String) {
  def f(someOtherArg: String) = ??? // uses arg
  def g() = ??? // uses arg
}

// elsewhere
def someFunc() = {
  val aclassInstance = new AClass("someFunc")
  import aclassInstance._

  val x = f("foo")
  val y = g()
}
1 Like

That I didn’t realize that it’s an option. I guess this is what @soronpo was refferring to too.

Well if this is possible anyway, I see it as an argument in favour of my proposal, since right now aclassInstance val has to be created despite there being no intention to use it, which falls into the definition of noise for me.

I don’t see how would you not use the created instance… if that would be the case, you wouldn’t need the import at all…

It’s also quite irregular IMO with respect to the rest of the language, it will actually generate an instance implicitly, with a special casing syntax

Right now you can only import from a stable identifier, so e.g. you can’t import from a var or def.

Example https://scastie.scala-lang.org/3SvPOmj0TlWLCytPgX1nhQ

case class C(a: Int, b: String)

def cDef = C(util.Random.nextInt(), "a")
import cDef._ // won't compile
var cVar = cDef
import cVar._ // won't compile
val cVal = cVar // copy to a stable identifier
import cVal._ // now importing works
1 Like