简体   繁体   English

Scala case class vs object:它是如何实例化的?

[英]Scala case class vs object: how is it instantiated?

Some context so that this question actually makes some sense.一些上下文,以便这个问题实际上是有道理的。

I have a trait from which I extend a case class and an object.我有一个特征,我从中扩展了一个案例 class 和一个 object。 I have a method that pattern matches to decide which to pull based on given conditions.我有一种模式匹配的方法来决定根据给定条件提取哪个。 When I pattern match and get the case class, everything works fine.当我进行模式匹配并获得案例 class 时,一切正常。 But when I pattern match and get the object, an error is thrown.但是,当我进行模式匹配并获得 object 时,会引发错误。

Within the trait, I have methods that call the DB.在 trait 中,我有调用数据库的方法。 And I also have vals that need overriding.而且我也有需要覆盖的 val。

The curious thing is the error that is thrown when it the object is instantiated, is a DB specific error奇怪的是当 object 被实例化时抛出的错误,是一个特定于数据库的错误

java.sql.SQLInvalidAuthorizationSpecException: (conn=41) Transaction characteristics can't be changed while a transaction is in progress

Which led me on wild goose chase to hunt down whether the code was opening up another session unknowingly etc. But having checked my code, I knew I was passing around the one DB connection I had started and there wasn't any strange behaviour.这导致我大打出手,追查代码是否在不知不觉中打开了另一个 session 等。但是检查了我的代码后,我知道我正在传递我已经启动的一个数据库连接,并且没有任何奇怪的行为。

I figured, since my case class instance works, I wanted to see if converting my object into a case class would change anything.我想,由于我的案例 class 实例有效,我想看看将我的 object 转换为案例 class 是否会改变任何事情。

Having converted my object to a case class, I then got an NPE error thrown which pointed me directly to the errant line of code that was causing problems.将我的 object 转换为案例 class 后,我收到了一个 NPE 错误,它直接指向导致问题的错误代码行。 I then changed my vals to def in the trait and everything works fine.然后我将特征中的 val 更改为 def ,一切正常。

So my questions is: Why is it that when I converted the object to the case class, it then threw up the error that was the true culprit.所以我的问题是:为什么当我将 object 转换为案例 class 时,它会抛出真正的罪魁祸首。 Which is why I asked the question: how is a case class vs object instantiated?这就是我问这个问题的原因:如何实例化 class 与 object 的案例? Because I suspect this was the cause of the misleading error being thrown.因为我怀疑这是引发误导性错误的原因。

Feel free to correct my assumption if it is wrong.如果我的假设是错误的,请随时纠正我的假设。

Here is the crucial line:这是关键的一行:

I then changed my vals to def in the trait and everything works fine.然后我将特征中的 val 更改为 def ,一切正常。

The problem was almost certainly caused by an abstract val in the trait being used in the constructor before it had been initialised by the subclass.该问题几乎可以肯定是由构造函数中使用的trait中的抽象val在子类初始化之前引起的。

As a general rule, abstract values in a trait should always be def .作为一般规则, trait中的抽象值应始终为def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM