2014-11-22 97 views
4
> 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]

回答

7

什麼是字符串與INT?

這是一個交集類型。即此類型的值必須同時爲IntString

我不認爲這是可能的。

是的,這是一種無人居住的類型。但是,一般情況下,如果將IntString替換爲某些類型AB,則會得到PartialFunction[A with B, Unit],編譯器對此沒有特殊情況。

+1

那麼,它會* *讓你傳入null,用合適的演員。這沒有多大幫助,但它確實在技術上有用。 – 2014-11-22 17:57:41

+0

啊,我會預料到'A with B'只有在'B'是一個特質時纔有效。 – 2014-11-22 18:02:01

+0

我只用Scala 2.9.2測試過,因爲這是我得心應手的。不確定新版本的行爲是否有所不同。 – 2014-11-22 18:03:41

1

嗯,正如前面所說的,它是一個複合型,它適用於任何兩種(類,性狀),如下面的代碼:

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