Does the lazy val type access its evaluation?

As the title of the question says, is a type

member accessing that member's lazy val

score? Or is it just using its static type?

Here is some sample code I have implicit lazy val

and I would like to use its type in a method that accepts implicit val

with that type:

implicit lazy val nonSpaces: Array[(Point, Part)]

...

def randomNonSpaceCoordinate(implicit nonSpaces: this.nonSpaces.type): Point = nonSpaces(Utils.Random.randUpTo(nonSpaces.length))._1

+3


source to share


2 answers


Let's check:

scala> object Test {
     |   lazy val test: String = {println("bang!"); "value"}
     |   val p: this.test.type = null
     |   def testDef(p: this.test.type) = println(p)
     | }
defined module Test

scala> Test.testDef(Test.p)
null

scala> Test.testDef(Test.test)
bang!
value

      



Since you can see that type access only does not require lazy val to actually be evaluated.

+5


source


Not. Level-level computations (other than their "reflection" of the shadow self) are compilation.

You can check things like this:

scala> lazy val lv1 = { println("Initializing lv1"); "lv1" }
lv1: String = <lazy>

scala> def m1(s: lv1.type): Int = s.length
m1: (s: lv1.type)Int

scala> lv1
Initializing lv1
res5: String = lv1

      



However, you might want to consider using .type

it more closely like this, as it is a so-called depident-type path , in which case it is probably too narrow to be useful

scala> m1(lv1)
res6: Int = 3

scala> m1("42")
<console>:10: error: type mismatch;
 found   : String("42")
 required: lv1.type
              m1("42")

      

In your case, you will randomNonSpaceCoordinate

only be able to call with nonSpaces

, which makes it a little pointless to pass it as an argument at all.

+5


source







All Articles