问题描述
我在项目中使用 nscala-time(Joda Time 的包装器)和 slick.我正在尝试使用此子句向数据库写入一行:
I am using nscala-time (wrapper for Joda Time) and slick for a project. I'm trying to use this clause to write a line to the database:
Article.insert(0,"title1", "hellothere", DateTime.now.getMillis.asInstanceOf[Timestamp])
显然 Slick 不支持 Joda Time 中定义的dateTime"类型,我必须使用 java.sql.Timestamp
代替.所以我决定在 insert
方法内部做一些转换,使用asInstanceOf".不幸的是,Scala 很快告诉我 Java.Long 不能转换为 Java.sql.Timestamp.然后我用了这个:
Apparently Slick does not support "dateTime" type defined in Joda Time, and I have to use java.sql.Timestamp
instead. So I decide to do a little conversion inside the insert
method, using "asInstanceOf". Unfortunately, Scala quickly tells me that Java.Long cannot be converted to Java.sql.Timestamp. Then I used this:
val dateTime = new DateTime();
val timeStamp = new Timestamp(dateTime.getMillis());
Article.insert(0,"title1", "hellothere", timeStamp)
这很神奇,我只剩下困惑.
This magically works, and all I'm left with is confusion.
我怎样才能以一种方式而不是另一种方式转换它?我应该使用与 asInstanceOf
不同的转换吗?
How can I convert it one way but not the other? Should I use a different conversion than asInstanceOf
?
推荐答案
你误解了 asInstanceOf
的作用:asInstanceOf
不转换任何东西.它所做的是对编译器撒谎,告诉它相信某事而不是使用它所拥有的知识.
You misunderstand what asInstanceOf
does: asInstanceOf
doesn't convert anything. What it does is lie to the compiler, telling it to believe something instead of going with the knowledge it has.
所以,你有一个Long
,然后你得到一个Long
,但假装它是一个Timestamp
,这显然不是工作.
So, you had a Long
, and then you got a Long
, but pretended it was a Timestamp
, which obviously doesn't work.
我有一个关于 asInstanceOf
的简单建议:永远不要使用它.
I have a simple recommendation regarding asInstanceOf
: never use it.
这篇关于Scala 转换 long 到 datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!