2010-04-15 49 views
3

(注意,左值實際上是從C語法的術語,我不知道它叫什麼斯卡拉!)你可以在Scala中返回一個可賦值的左值嗎?

努力學習斯卡拉......今天晚上我工作的一個內部DSL對於可能類似於PHP語法的動態範圍的語言。

我的REPL是:歡迎來到Scala版本2.7.6.final(Java HotSpot™客戶端VM,Java 1.6.0)。

我有一些虛構的示例代碼:

 

class $(any: Any) { 
    def update(sym: Symbol, any: Any) { println("line 2 executed");} 
    def ->(sym: Symbol) : $ = { println("line 1 executed"); return this } 
    def update(any: Any) { println("line 3 executed");} 
} 

預期以下工作:

scala> var a = new $(0) 
a: $ = [email protected] 

scala> a('x) = "blah" 
line 2 executed 

在另一方面,爲什麼下面沒有調用1參數更新方法?

 
scala> a = 1 
:6: error: type mismatch; 
found : Int(1) 
required: $ 
     a = 1 
     ^

雖然做了一些試驗和錯誤,我發現這句法好奇:

 
scala> class A { def this_= { print("hello") } } 
defined class A 

scala> var a = new A 
a: A = [email protected] 

scala> a = 2 
:6: error: type mismatch; 
found : Int(2) 
required: A 
     a = 2 
     ^

scala> a.this_ 
:7: error: value this_ is not a member of A 
     a.this_ 
     ^

什麼是過度覆蓋「THIS_」上面的意思嗎?它在哪裏?

最後,我想這個工作:

 
a->'x = "blah" 

感謝

+3

最後一個例子不工作,因爲該方法實際上是'THIS_ =''不該this_''='限定的方法(雖然,如果不使用,則該方法將返回'Unit')和無之間的空間時,需要心不是這兩個scalac只是假定你想要'this_ ='方法。 林相當肯定,你想要做什麼心不是可能的,因爲其特殊的'='的方法,但將它與其他一些功能輕鬆可行的(如:'< - ','<=') – 2010-04-15 01:36:26

回答

8
def this_= { print("hello") } 

你似乎認爲這是方法this_等於{ print("hello") }。相反,這是方法this_=,它使用過程樣式聲明(即不等號)。

這是最經常使用這樣的:

scala> class A { 
    | private var _x = "" 
    | def x = _x 
    | def x_=(s: String) = _x = s.toUpperCase 
    | } 
defined class A 

scala> new A 
res0: A = [email protected] 

scala> res0.x 
res1: java.lang.String = 

scala> res0.x = "abc" 

scala> res0.x 
res2: java.lang.String = ABC 

然而,當您巧合使用具有特殊意義的語法(id_=),它只是一個標識符。任何標識符都會混合使用字母數字字符和其他符號,並由下劃線字符分隔。

最後,不,在Scala中沒有可賦值的左值。你可以有這樣的事情:

id(key) = value // with update 
id.key = value // with key_=, as long as key also exists and is public 
id += value  // or any other method containing "=" as part of its name 

舉例來說,你可以這樣做:

scala> class A { 
    | private var _x = "" 
    | def :=(s: String) = _x = s.toUpperCase 
    | override def toString = "A("+_x+")" 
    | } 
defined class A 

scala> val x = new A 
x: A = A() 

scala> x := "abc" 

scala> x 
res4: A = A(ABC) 

=,其本身被保留。順便說一句,在Scala中沒有引用傳遞 - 你永遠不能改變作爲參數傳遞的變量的值。

+0

謝謝,:=想法實際上是一個相當不錯的解決方法,如果「=」不起作用將不起作用 – 2010-04-15 06:40:38

1

我想你需要的是隱式轉換。

scala> case class Test (val x: Int) 
defined class Test 

scala> implicit def testFromInt (x: Int) = new Test (x) 
testFromInt: (Int)Test 

scala> var a = new Test (3) 
a: Test = Test(3) 

scala> a = 10 
a: Test = Test(10) 

順便說一句,我相信你不應該使用$作爲標識符,它通常用於編譯器生成的類/函數。

+0

居然沒有任何理由在Scala中避免$ - 它在生成的字節碼中轉義爲$美元。 – 2010-04-15 15:32:00

相關問題