4

I'm kinda new to scala. I got into trouble while trying to return object type.

Here is the code.

It shows "error: not found: type A"

object A{}

object B {
  def getInstance() : A = {
    return A
  }
}

If I do similar kind of thing with class instance, it wont show any problem.

class A{}

object B {
  def getInstance() : A = {
    return new A
  }
}

As far as I know object type is a singleton instance of class. What am I missing here?

2 Answers 2

4

Compiler complains that can not find type A because in your case A is a name of an object not a type, use A.type to refer to type, like this:

object A

object B {
  def getInstance: A.type = A
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just would like to add that with type inference you could actually omit return type and write just def getInstance = A
3

Because object is a singleton is does not define a type, instead in defines a value.

If you would look at the Java equivalent, using scala object produces the:

A$ class //
A$.MODULE$ // singleton instance definition

The type is however masked and can be accessed via A.type.

Using return is also not necessary in Scala. The last statement position in a block is automatically interpreted as return value.

class A{}

object B {
  def getInstance() : A = new A
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.