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

How to pass implicit value to a function?

我是 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
}

此代码无效。但这确实。

class Person{

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

class NewPerson{
    implicit val name: String = "a Shamir"
    def whoAmI: Unit = {
        val p: Person = new Person
        p.whoAmI
    }
}

object Main extends App {
    val person: NewPerson = new NewPerson
    person.whoAmI
}

我想要这样的东西。

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()(name)
}

可能吗?

您应该指定 NewPerson.whoAmI 采用隐式参数,它将在 Person.whoAmI

中使用
 class Person {

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

  class NewPerson {
    def whoAmI()(implicit name: String): 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()(name)
  }

首先,你应该为隐式选择一个更精致的类型,将原始类型作为隐式不是很整洁。 StringInt 隐式在生产代码中总是一个坏主意。现在在学习,习惯就好。

假设我们有:

case class Name(name: String)

现在了解隐式传播和转发很重要。隐式通过继承或更高范围传播,因此您要么扩展具有您正在寻找的隐式的东西,要么将其导入更高范围。

最好在第二组函数参数中定义隐式,如下所示:

def test(p1: T1, p2: T2..)(implicit ev1: E1, ev2: E2): ReturnType = {}

这是因为当您调用带有括号的函数 whoAmI 时,编译器期望显式传递隐式,这使使用隐式的意义消失了。

所以当你这样写 whoAmI 时:

def whoAmI(implicit name: Name): Unit

并且您这样调用:whoAmI()(),编译器希望您手动传递名称。隐式是 "hidden",这意味着一旦定义它们就意味着 "just there",只要您遵守范围规则,它们就可以用来消除键入样板文件。

class Person {

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

class NewPerson {
    // Here your implicit is mising
    def whoAmI()(implicit name: Name): Unit = {
        val p: Person = new Person
        p.whoAmI
    }
}

object Main extends App {
    implicit val name: Name = Name("a Shamir")
    val person: NewPerson = new NewPerson
    // Now you don't actually need to manually type in the implicit
    person.whoAmI()
}