Movatterモバイル変換


[0]ホーム

URL:


This page is no longer maintained — Please continue to the home page atwww.scala-lang.org

Home

Scala Main Menu

Home »A Tour of Scala » A Tour of Scala: Higher-Order Functions

A Tour of Scala: Higher-Order Functions

Created by admin on 2008-07-05. Updated: 2010-01-20, 11:26

Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Here is a function apply which takes another function f and a value v and applies function f to v:

def apply(f: Int => String, v: Int) = f(v)

Note that methods are automatically coerced to functions if the context requires this.

Here is an example:

 

class Decorator(left: String, right: String) {def layout[A](x: A) = left + x.toString() + right}object FunTestextends Application {def apply(f: Int => String, v: Int) = f(v)val decorator =new Decorator("[","]")  println(apply(decorator.layout, 7))}

 

Execution yields the output:

[7]

In this example, the method decorator.layout is coerced automatically to a value of type Int => String as required by method apply. Please note that method decorator.layout is a polymorphic method (i.e. it abstracts over some of its signature types) and the Scala compiler has to instantiate its method type first appropriately.

 

Scala Quick Links

Featured News

User login


will be sent securely

Create new account

Retrieve lost password

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland


[8]ページ先頭

©2009-2026 Movatter.jp