小编Sha*_*lla的帖子

Scala:有没有一种方法可以将类型别名视为与其别名的类型不同?

给出以下示例:我想截断字符串以满足某些长度限制,例如与 SQL 类型的兼容性。

type varchar8 = String

implicit def str2Varchar8(str: String): varchar8 = str.take(8)

val a: varchar8 = "abcdefghi"

// wanted: "abcdefgh", actual result:
a: varchar8 = abcdefghi
Run Code Online (Sandbox Code Playgroud)

编译器似乎没有区分这两种类型。

给定类型别名type A = String,我想要实现的是:

  1. 避免运行时分配(即包装类)
  2. String仅当映射到类型别名时才应用断言/转换的能力AA即直接使用类型别名作为输入时避免进一步的断言/转换

验证示例:

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 …
Run Code Online (Sandbox Code Playgroud)

casting scala typechecking implicit-conversion

5
推荐指数
1
解决办法
1292
查看次数