标签: implicits

如何将隐式值传递给函数?

我是新手scala。我正在学习implicit variables。如何将隐式变量传递给调用另一个将使用该变量的函数的函数。我知道这个问题看起来很愚蠢。看看我写的代码就知道了。

class Person{

    def whoAmI(implicit name: String): Unit = {
        println(s"I am $name")
    }
}

class NewPerson{
    def whoAmI: Unit = {
        val p: Person = new Person
        p.whoAmI
    }
}

object Main extends App {
    implicit val name: String = "a Shamir"
    val person: NewPerson = new NewPerson
    person.whoAmI
}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用。但这确实。

class Person{

    def whoAmI(implicit name: String): Unit = {
        println(s"I am $name")
    }
}

class NewPerson{
    implicit val name: String = "a Shamir" …
Run Code Online (Sandbox Code Playgroud)

scala implicit implicit-conversion implicits

1
推荐指数
1
解决办法
2505
查看次数

不清楚为什么我的范围内隐含转换不被接受为"隐含证据"

我一直在尝试隐式转换,而且我对使用这些转换的'enrich-my-libray'模式有了很好的理解.我试图将我对基本隐含的理解与隐含证据的使用结合起来......但我误解了一些关键的东西,如下面的方法所示:

import scala.language.implicitConversions

object Moo extends App {

  case class FooInt(i: Int)
  implicit def cvtInt(i: Int) : FooInt = FooInt(i)
  implicit def cvtFoo(f: FooInt) : Int = f.i

  class Pair[T, S](var first: T, var second: S) {
    def swap(implicit ev: T =:= S, ev2: S =:= T) {
      val temp = first
      first = second
      second = temp
    }

    def dump() = {
      println("first is " + first)
      println("second is " + second)
    }
  }

  val x  = new Pair(FooInt(200), …
Run Code Online (Sandbox Code Playgroud)

scala typeclass implicit-conversion implicits

0
推荐指数
1
解决办法
81
查看次数

Scala编译器如何使用`<:<`来合成隐式证据?

鉴于Scala中的这个(公认的设计)代码片段:

object Main extends App {

  class X { def foo = 1 }

  def f[A](value: A)(implicit ev: A <:< X) = { value.foo }

  println(f(new X()))

}
Run Code Online (Sandbox Code Playgroud)

Scala编译器做了什么来传递这个?我已经查看了一些代码,Predef但我不了解实现.请详细说明一步一步.

scala implicits

0
推荐指数
1
解决办法
106
查看次数

为Scala的对象设置隐式实例变量

我有一个带有一堆实用程序方法的Scala对象,每个方法都使用一个隐式方法参数 s

object MyObject {
 def a(implicit s:String) = ???
 def b(implicit s:String) = ???
 def c(implicit s:String) = ???
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢implicit s:String在每个参数列表中需要这个的事实.有没有办法只设置s一次变量(即首次访问对象时).对于一堂课,我会做这样的事情:

class MyClass(implicit s:String) {
 def a() = ???
 def b() = ???
 def c() = ???
}
Run Code Online (Sandbox Code Playgroud)

scala implicits

0
推荐指数
1
解决办法
613
查看次数