scala - scala 中的类型安全响应是否可能?

标签 scala casting case typechecking respond-to

在 scala 中使用 case 构造进行类型安全的转换很容易。以下代码确保 square仅在具有相应类型的对象上调用。

class O
class A extends O {
    def square(i: Int):Int = { i*i }
}
class B extends O {
    def square(d: Double):Double = { d*d }
}
class C extends O {}

def square(o: O) = o match {
    case a:A => print(a.square(3))
    case b:B => print(b.square(3.0))
    case c:C => print(9)
    case _ => print("9")
}

另一方面,在某些情况下,使用类型信息进行转换并仅检查 {def square(Int): Int} 的可用性并不那么容易。就足够了。 scala 中是否有一个构造允许做类似于
def square(o: O) = o match {
    case a:{def square(Int):Int} => print(a.square(3))
    case b:{def square(Double):Double} => print(b.square(3.0))
    case _ => print("9")
}

使用隐式证据参数,可以根据其他方法的可用性来定义方法。是否也可以仅在定义时调用它们?

最佳答案

结构类型表示成员的非继承约束可用性,因此如果您希望方法仅接受带有特定方法的值,请说 def square(i: Int): Int ,你使用这个符号:

class Squaring {
  type Squarable = { def square(i: Int): Int }
  def squareMe(s: Squarable): Int = s.square(17)
}

class CanSquare { def square(i: Int) = i * i }

val cs1 = new CanSquare
val s1 = new Squaring

printf("s1.squareMe(cs1)=%d%n", s1.squareMe(cs1))


s1.squareMe(cs1)=289

您应该知道结构类型是通过反射实现的,但是从 Scala 2.8 开始,反射信息在逐个类的基础上缓存在调用站点(提供值的实际类)。

关于scala - scala 中的类型安全响应是否可能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3434522/

相关文章:

scala - 如何在 Play/Scala 中声明名为 'type' 的变量?

scala - 为什么 TraversableOnce.toSeq 返回一个流?

c++ - 我需要转换无符号字符吗?

c++ - 为什么我的模板特化检查不足以正确处理相应的类型?

带/不带选项的 BASH 脚本和参数

scala - 斯卡拉结合笛卡尔乘积和 map

mysql - 使用 Spark Dataframe 更新 Mysql 列值

java - 将 long 显式转换为 int 并将 long 隐式转换为 float

MySQLIntegrityConstraintViolationException : Column '' cannot be null

ruby - 试图在 case 语句中引用更早的 'case'