Skip to content

Scala:Underscore

Scala 언더스코어(_)의 활용에 대한 내용.

Import all

java의 import *

import java.util._
val date = new Date()

var initialization to default value

기본 초기값.

class Foo {
  // we must be on class level
  var i:Int = _ // i = 0
  var s:String = _ // s = null

  def f {
    var i:String = _ // ERROR!! local variables must be initialized
  }
}

Unused variables

고차함수

(1 to 5) foreach { (x: Int) => println("one more") }

다음과 같이 변환할 수 있다:

// variable x isn't used in right hand
// side of "=>" : let it unamed
(1 to 5) foreach { _ => println("one more") }

패턴 매칭

def inPatternMatching1(s:String) {
  s match {
    case "foo" => println("foo !")
    case _ => println("not foo")
  }
}

다음과 같이 변환할 수 있다:

def inPatternMatching1(s:String) {
  s match {
    case "foo" => println("foo !")
    case _ => println("not foo")
  }
}

Anonymous parameters

고차함수

(1 to 10) map { x => x + 1 }
// same as
(1 to 10) map { _ + 1 }

// but that does not work
// the compiler gives a new fresh name for each _
// (1 to 10) map { _ / 2 + _ }

Works with several elements

(1 to 10).foldLeft(0) { (x, y) => x + y }
// same as:
(1 to 10).foldLeft(0) { _ + _ }

partial functions

def f (i:Int) : String = i.toString

def g = (x: Int) => f(x)
// same as
def g2 = f _
// same as
def f2 = (_: String).toString

그리고

def u(i:Int)(d:Double) : String = i.toString + d.toString

def v = u _ // v : (Int) => (Double) => String
// same as: def v = (x:Int) => (y:Double) => u(x)(y)

def w1 = u(4) _ // w1: (Double) => String
// same as: def w1 = (y:Double) => u(4)(y)

def w2 = u(_:Int)(2.0) // w2: (Int) => String
// same as: def w2 = (x:Int) => u(x)(2.0)

Don't import name in namespace

import java.util.{
  Date => _, // remove Date from namespace
  _ // import everything from java.util
}

Syntactic sugar for existential type

java의 Generic wildcard (?)

def size(objs: List[T] forSome { type T } ) : Int = objs.size
// same as:
def size2(objs:List[_]) : Int = objs.size

Sccessors in tuples

("foo", "bar")._2 // getter for "bar"

Example

class Underscores {
    import collection.{ Map => _ , _ }

    var count : Int = _

    def sum = (_:Int) + (_:Int)
    def sum2(a:Int)(b:Int) = a+b
    def offset = sum2(count) _

    def sizeOf(l:Traversable[_]) : Unit = l match {
        case it:Iterable[Int] => count = (0/:it)(_ + _)
        case s:Seq[_] => s.foreach( _ => count = count + 1)
        case _ => println(offset(l.size))
    }
}

See also

Favorite site