2016-04-09 68 views
-2

Scala中的隱式轉換和隱式參數之間是否存在關係?Scala中的隱式轉換和隱式參數之間的關係是什麼?

我不知道如何知道不同類型的implicits是什麼或他們的解析規則是什麼。

我只關心爲什麼這兩個概念具有相同的名稱。

+3

這回答了這個問題:http://stackoverflow.com/questions/5598085/where-does-scala-look-for-implicits –

+0

@GiovanniCaporaletti如何回答這個問題? –

+0

@MichaelLafayette它詳細解釋了隱式轉換和隱式參數是什麼以及編譯器如何管理它們。我真的不知道還有什麼可以添加到這一點。它還將所有內容與視圖邊界和上下文邊界放在一起,這是一個全面的答案。 –

回答

3

據我所知,沒有任何直接的關係,除了它們共享相同的關鍵字。

但他們可以以有趣的方式等組合:

class Foo 
class Bar 
class FooBar(foo: Foo, bar: Bar) 

implicit val foo = new Foo 
implicit val bar = new Bar 

implicit def fooBar(implicit foo: Foo, bar: Bar): FooBar = new FooBar(foo, bar) 

implicitly[FooBar] 

implicit conversion(花哨的名字,但實際上只不過是一個隱含的接受參數更多)可以接受implicit parameters行事非常像一個implicit val(給定含義被定義)。繁榮。

3

的隱式轉換類型A鍵入B是一個隱式功能A => B

隱含的畫質使得可用的隱函數:

// two types 
class A 
class B 
// implicit conversion from A to B 
implicit def aToB(a: A): B = { 
    println("aToB"); 
    new B 
} 
// we now have a Function[A, B] aka A => B in the implicit scope 
val f = implicitly[A => B] 
f(new A) 
> aToB 
res1: B = [email protected] 

隱含的功能,可以隱式轉換:

class IntExtension(x: Int) { def isPositive = x > 0 } 
implicit val intToIntExtensions: Int => IntExtension = x => new IntExtension(x) 
> 1.isPositive 
res2: Boolean = true 
+0

讓我看看我是否正確理解你。隱式地[A => B]將返回對aToB的引用。你可以給這個引用一個新的A,它會返回一個新的B.隱式的val服務的功能與隱式的def相同。但是隱式參數的函數如foo(int:Int)(隱式bar:Bar)呢? –