time 的单位是什么呢? 可能是毫秒、秒、分钟... 现在还不清楚,很容易出错。 一个著名的例子是:某个火星气候轨道器错误地撞向了火星大气层,背后的原因是控制它的软件是由一个外包公司开发的,它产生的输出单位不是 NASA 所期望的。它所输出的结果单位是磅力秒(lbf·s),但是 NASA 期望的单位是牛顿秒(N·s)。这次任务的总成本是3.276亿美元,以完全失败告终。正如你所看到的,测量单位的混乱可能会产生非常严重的后果。
interface Timer {
fun callAfter(time: Int, callback: ()->Unit)
}
interface Timer {
fun callAfter(timeMillis: Int, callback: ()->Unit)
}
interface User {
fun decideAboutTime(): Int
fun wakeUp()
}
interface Timer {
fun callAfter(timeMillis: Int, callback: ()->Unit)
}
fun setUpUserWakeUpUser(user: User, timer: Timer) {
val time: Int = user.decideAboutTime()
timer.callAfter(time) {
user.wakeUp()
}
}
inline class Minutes(val minutes: Int) {
fun toMillis(): Millis = Millis(minutes * 60 * 1000)
// ...
}
inline class Millis(val milliseconds: Int) {
// ...
}
interface User {
fun decideAboutTime(): Minutes
fun wakeUp()
}
interface Timer {
fun callAfter(timeMillis: Millis, callback: ()->Unit)
}
fun setUpUserWakeUpUser(user: User, timer: Timer) {
val time: Minutes = user.decideAboutTime()
timer.callAfter(time) { // ERROR: Type mismatch
user.wakeUp()
}
}
fun setUpUserWakeUpUser(user: User, timer: Timer) {
val time = user.decideAboutTime()
timer.callAfter(time.toMillis()) {
user.wakeUp()
}
}
inline val Int.min
get() = Minutes(this)
inline val Int.ms
get() = Millis(this)
val timeMin: Minutes = 10.min
@Entity(tableName = "grades")
class Grades(
@ColumnInfo(name = "studentId")
val studentId: Int,
@ColumnInfo(name = "teacherId")
val teacherId: Int,
@ColumnInfo(name = "schoolId")
val schoolId: Int,
// ...
)
inline class StudentId(val studentId: Int)
inline class TeacherId(val teacherId: Int)
inline class SchoolId(val studentId: Int)
@Entity(tableName = "grades")
class Grades(
@ColumnInfo(name = "studentId")
val studentId: StudentId,
@ColumnInfo(name = "teacherId")
val teacherId: TeacherId,
@ColumnInfo(name = "schoolId")
val schoolId: SchoolId,
// ...
)
interface TimeUnit {
val millis: Long
}
inline class Minutes(val minutes: Long): TimeUnit {
override val millis: Long get() = minutes * 60 * 1000
// ...
}
inline class Millis(val milliseconds: Long): TimeUnit {
override val millis: Long get() = milliseconds
}
fun setUpTimer(time: TimeUnit) {
val millis = time.millis
//...
}
setUpTimer(Minutes(123))
setUpTimer(Millis(456789))
typealias NewName = Int
val n: NewName = 10
typealias ClickListener =
(view: View, event: Event) -> Unit
class View {
fun addClickListener(listener: ClickListener) {}
fun removeClickListener(listener: ClickListener) {}
//...
}
typealias Seconds = Int
typealias Millis = Int
fun getTime(): Millis = 10
fun setUpTimer(time: Seconds) {}
fun main() {
val seconds: Seconds = 10
val millis: Millis = seconds // 不会编译报错
setUpTimer(getTime())
}