ilango
ilango

Reputation: 1287

Trying to understand Precedence Rule 4 in Scala In Depth Book

I am trying to understand the 4th rule on Precedence on Bindings on page 93 in Joshua Suareth's book Scala in depth.

According to this rule:

definitions made available by a package clause not in the source file where the definition occurs have lowest precedence.

It is this rule that I intend to test.

So off I went and tried to follow Josh's train of thought on Page 94. He creates a source file called externalbindings.scala and I did the same, with some changes to it as below

package com.att.scala

class extbindings {
  def showX(x: Int): Int = {
    x
  }

  object x1 {
    override def toString = "Externally bound obj object in com.att.scala"
  }
}

Next he asks us to create another file that will allow us to test the above rule. I created a file called precedence.scala:

package com.att.scala

class PrecedenceTest { //Josh has an object here instead of a class

  def testPrecedence(): Unit = { //Josh has main method instead of this
    testSamePackage()
    //testWildCardImport()
    //testExplicitImport()
    //testInlineDefinition()
  }

  println("First statement of Constructor")
  testPrecedence
  println("Last statement of Constructor")

  def testSamePackage() {
    val ext1 = new extbindings()
    val x = ext1.showX(100)
    println("x is "+x)
    println(obj1) // Eclipse complains here
  }
}

Now, Josh is able to print out the value of the object in his example by simply doing the <package-name>.<object-name>.testSamePackage method on the REPL. His output is:

Externally bound x object in package test

In my versions, the files are in Eclipse and I have my embedded Scala interpreter.

Eclipse complains right here: println(obj), it says: not found value obj1

Am I doing something obviously wrong in setting up the test files? I would like to be able to test the rule I mentioned above and get the output:

Externally bound obj object in package com.att.scala

Upvotes: 1

Views: 93

Answers (2)

kiritsuku
kiritsuku

Reputation: 53348

I haven't read the book, thus I'm not really sure if your code shows what the book wants to tell you.

Nevertheless, the error message is correct. obj1 is not found because it doesn't exist. In your code it is called x1. Because it is a member of extbindings you have to access it as a member of this class:

println(ext1.x1)

If x1 is defined outside of class extbinding, in scope of package com.att.scala, you can access it directly:

println(x1)

If it is defined in another package you have to put the package name before:

println(com.att.scala2.x1)

To simplify some things you can import x1:

import ext1.x1
println(x1)

Finally a tip to improve your code: name types in UpperCamelCase: extbindings -> Extbindings, x1 -> X1

Upvotes: 4

Edmondo
Edmondo

Reputation: 20080

If you replace a singleton object with a class, you will need to create an instance of that class.

Upvotes: 3

Related Questions