English 中文(简体)
Scala s 函数作为参数使用
原标题:Scala s function as parameter usage
  • 时间:2012-05-22 06:19:10
  •  标签:
  • scala
class ClosureClass {
  def printResult[T](f: => T) = {
    println("choice 1")
    println(f)
  }

  def printResult[T](f: String => T) = {
    println("choice 2")
    println(f("HI THERE"))
  }
}

object demo {
  def main(args: Array[String]) {
    val cc = new ClosureClass
    cc.printResult()   // call 1
    cc.printResult("Hi")  // call 2
  }
}

我玩上面的代码,结果给我看。我有两个问题

1) 为什么一号电话和二号电话 都进入选择1?

2) 我如何通过参数才能进入选择 2。

谢谢

choice 1
()
choice 1
Hi
最佳回答

类型 表示 是一个逐名参数。 这意味着 是类型 T , 使用该函数时将评价该函数中传入的表达式(而不是调用函数时)。

类型 string {gt; T 表示 f function[String,T] , 即从 string T 的函数。

当您用 "Hi" (一个 String)作为参数时, Scala看到, printResult 有两个选择:

1) :在此情况下, T String有约束力,这很好。

2) string {gt;T :这行不通,因为 string 不是从 string 到任何东西的函数...它根本不是函数。

您如何修正它取决于您想要做什么。 如果您只想修正 < code> printResult < /code> 是如何被调用的, 那么您会把它调用 :

val g: (String => String) = (s: String) => s + "***"
cc.printResult(g)

指纹:

choice 2
HI THERE***

既然现在您现在正正确通过 函数 , /sting 到某些 T 在这里是 >T , 因为函数只是将 添加到通过的内容的末尾, 并返回修改过的字符串 。

问题回答

暂无回答




相关问题
How to flatten a List of different types in Scala?

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]] I tried to zip them and I ...

To use or not to use Scala for new Java projects? [closed]

I m impressed with Twitter and investigating to use Scala for a new large scale web project with Hibernate and Wicket. What do you think about Scala, and should I use it instead of Java? EDIT: And, ...

Why does Scala create a ~/tmp directory when I run a script?

When I execute a Scala script from the command line, a directory named "tmp" is created in my home directory. It is always empty, so I simply deleted it without any apparent problem. Of course, when I ...

Include jar file in Scala interpreter

Is it possible to include a jar file run running the Scala interpreter? My code is working when I compile from scalac: scalac script.scala -classpath *.jar But I would like to be able to include a ...

Scala and tail recursion

There are various answers on Stack Overflow which explain the conditions under which tail recursion is possible in Scala. I understand the limitations and how and where I can take advantage of tail ...