【问题标题】:What is "String with Int" supposed to mean?“带 Int 的字符串”应该是什么意思?
【发布时间】:2014-11-22 17:48:38
【问题描述】:
> val foo: PartialFunction[String, Unit] = { case i: String => }
foo: PartialFunction[String,Unit] = <function1>

> val bar: PartialFunction[Int, Unit] = { case i: Int => }
bar: PartialFunction[Int,Unit] = <function1>

> foo orElse bar
PartialFunction[String with Int,Unit] = <function1>

String with Int? 是什么。我认为这根本不可能。

> (foo orElse bar)(new String with Int)
error: illegal inheritance from final class String
  (foo orElse bar)(new String with Int)
                       ^
error: class Int needs to be a trait to be mixed in
  (foo orElse bar)(new String with Int)
                                   ^

不应该是PartialFunction[Nothing,Unit]吗?

【问题讨论】:

    标签: scala types type-inference


    【解决方案1】:

    什么是带 Int 的字符串?

    这是一个交叉点类型。 IE。此类型的值必须同时为IntString

    我认为这是不可能的。

    是的,这是一种无人居住的类型。但是,一般来说,如果您将IntString 替换为某些类型AB,您将得到PartialFunction[A with B, Unit],并且编译器对此没有特殊情况。

    【讨论】:

    • 好吧,它允许您通过适当的演员表传入 null。这没有多大帮助,但在技术上确实有效。
    • 啊,我原以为 A with B 只有在 B 是一个特征时才有效。
    • 我只用 Scala 2.9.2 测试过,因为那是我得心应手的。不确定新版本的行为是否会有所不同。
    • @PaulDraper 只有当B 是一个特征时它才能出现在extends 中,但它对于AB 的任何类型都是有效的。
    • 次要注意,在 Scala 中,它们通常称为 复合类型 而不是 交集类型,因为它们的行为不像正确的集合交集将。即,A with B with CA with C with B 不同。见:lampwww.epfl.ch/~emir/bqbase/2005/02/23/compoundinter.html
    【解决方案2】:

    嗯,如前所述,它是一种复合类型,它适用于任何两种类型(类、特征),如下代码所示:

    class B
    class C extends B
    class D extends C
    
    val bf: PartialFunction[B, Unit] = {case b: B => println("some b") }
    val cf: PartialFunction[C, Unit] = {case c: C => println("some c") }
    val g = bf orElse cf
    
    g(new D) // some b
    

    只是有时在某些情况下它缺乏意义。这些链接可能很有用:

    http://www.scala-lang.org/old/node/110

    http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#compound-types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 2015-08-28
      • 2011-06-05
      • 2018-05-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多