【发布时间】:2018-10-03 17:54:33
【问题描述】:
给定以下示例:我想截断字符串以满足某些长度限制,例如与 SQL 类型的兼容性。
type varchar8 = String
implicit def str2Varchar8(str: String): varchar8 = str.take(8)
val a: varchar8 = "abcdefghi"
// wanted: "abcdefgh", actual result:
a: varchar8 = abcdefghi
编译器似乎没有区分这两种类型。
给定一个类型别名type A = String,我想要实现的是:
- 避免运行时分配(即包装类)
- 仅在从
String映射到类型别名A时应用断言/转换的能力。即直接使用类型别名A作为输入时避免进一步的断言/转换
验证示例:
type NotNullA = A
def method(a: A) = if(a != null)
_method(a: NotNullA) // explicit typing
else
???
// "a" at runtime is a String but we consider it validated, instead relying on the type system
protected def _method(a: NotNullA) = ???
protected def _otherMethod(a: NotNullA) = ???
有没有一种方法可以将类型别名与它们别名的类型分开处理 - 从而使它们之间的隐式转换和类型检查成为可能?是否有其他一些编码/技术可以完成这项工作?
Side:我似乎记得两个 是分开的,并且类型和别名是不同的(与类型数量问题无关)。我之前的代码是这样的:
type FieldAType = Int
// and in a different class
def method(a: FieldAType) = ???
val b: FieldAType = 1
method(b) // worked
val c: Int = 1
method(c) // compiler error
method(c: FieldAType) // worked
但是,我无法重现此问题(可能是由于 Scala 版本较旧 - 目前使用的是 2.11.8)
【问题讨论】:
标签: scala casting implicit-conversion typechecking