KAs
KAs

Reputation: 1868

duplicate case class name in the same package under different files in Scala

Here's the two java scala files:

--A1.scala--

case class Result(a: String)

class A1    {
    ...
}


--B1.scala--

case class Result(a: String, b: String)

class B1    {
    ...
}

In class B1, Result case class is applied, but actually, it use Result case class in A1.scala as default (weirdly). Is there any reasons why this is happening and how could I solve this case?

Upvotes: 0

Views: 1321

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170815

It doesn't matter they are case classes: you can't have two classes with the same name in one package. Strictly speaking, it is possible by not using standard Java classloaders: e.g. OSGi bundles allow you to have same class name in two different bundles, but this is very likely an overkill.

If they are compiled together (in the same subproject) you should get a compilation error, so it seems they aren't. In which case even if it appears to work during development only one of the classes will be picked at runtime.

how could I solve this case

Don't use same name for them. Or put them into the companion objects for your classes:

-- A1.scala
class A1 { ... }

object A1 { 
  case class Result(a: String)
}

-- B1.scala
class B1 { ... }

object B1 {
  case class Result(a: String, b: String)
}

In this case you refer to them as A1.Result and B1.Result.

Upvotes: 2

Related Questions