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

Sha*_*lla 5 casting scala typechecking implicit-conversion

给出以下示例:我想截断字符串以满足某些长度限制,例如与 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 def _method(a: NotNullA) = ???
protected def _otherMethod(a: NotNullA) = ???
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以将类型别名视为与它们别名的类型分开,从而使它们之间的隐式转换和类型检查成为可能?是否有其他编码/技术可以完成这项工作?

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

但是,我无法重现此问题(可能是由于较旧的 Scala 版本 - 目前使用 2.11.8)

mkU*_*tra 2

我建议您查看softwaremill.scala-common.tagging库。

  • 无运行时开销

  • 保护您的类型的可靠方法

只需添加导入并定义您的标记类型:

import com.softwaremill.tagging._

type EvenTag
type EvenInt = Int @@ EvenTag

object EvenInt {
  def fromInt(i: Int): Option[EvenInt] =
    if (i % 2 == 0) Some(i.taggedWith[EvenTag]) else None
}

def printEvenInt(evenInt: EvenInt): Unit = println(evenInt)

EvenInt.fromInt(2).foreach(printEvenInt)

val evenInt: EvenInt = 2 // Doesn't compile
printEvenInt(2) // Doesn't compile
Run Code Online (Sandbox Code Playgroud)

我们如何破解它?

val evenInt: EvenInt = 1.taggedWith[EvenTag]
Run Code Online (Sandbox Code Playgroud)

享受!