分享

=>在Scala中意义是什么,看到很多这样的符号

arsenduan 发表于 2015-3-12 23:56:12 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 4 56410

=>在Scala中意义是什么,看到很多这样的符号
j = 0
    val s2 = s.split(",").filter(_.trim.nonEmpty).foreach {
      item =>
        {
          j = j + 1
          println(item, j)
        }
    }

已有(4)人评论

跳转到指定楼层
hyj 发表于 2015-3-12 23:56:33
=> has several meanings in Scala, all related to its mathematical meaning as implication.


1. In a value, it introduces a function literal, or lambda. e.g. the bit inside the curly braces inList(1,2,3).map { (x: Int) => x * 2 }


2. In a type, with symbols on both sides of the arrow (e.g. A => T, (A,B) => T, (A,B,C) => T, etc.) it's sugar forFunction<n>[A[,B,...],T], that is, a function that takes parameters of typeA[,B...], and returns a value of type T.


  2.1  Empty parens on the left hand side (e.g. () => T) indicate that the function takes no parameters (also sometimes called a "thunk");


  2.2 Empty parens on the right hand side denote that it returns ()—the sole value of type Unit, whose name can also be written ()—confused yet? :)


A function that returns Unit is also known as a procedure, normally a method that's called only for its side effect.


3. In the type declaration for a method or function parameter, with no symbol on the left hand side (e.g.def f(param: => T)) it's a "by-name parameter", meaning that is evaluated every time it's used within the body of the function, and not before. Ordinary "by-value" parameters are evaluated before entry into the function/method.


4.  In a case clause, they separate the pattern (and optional guard) from the result expression, e.g.case x => y.

回复

使用道具 举报

271592448 发表于 2015-3-13 09:37:27
怎么不翻译一下呢?
回复

使用道具 举报

nettman 发表于 2015-3-14 13:35:50
271592448 发表于 2015-3-13 09:37
怎么不翻译一下呢?

Scala 支持定义匿名函数,匿名函数由参数列表,箭头连接符( =>)和函数体组成

// 定义匿名函数
  val cube = (x: Int) => x * x *x


x * x *x 是函数体


(x: Int)是匿名函数的参数

=>连接参数列表和函数体

参考:Scala 初级入门3:简洁的 Scala 语法
回复

使用道具 举报

feng01301218 发表于 2015-3-14 18:03:24
Scala 支持定义匿名函数,匿名函数由参数列表,箭头连接符( =>)和函数体组成

// 定义匿名函数
  val cube = (x: Int) => x * x *x


x * x *x 是函数体


(x: Int)是匿名函数的参数

=>连接参数列表和函数体

参考:Scala 初级入门3:简洁的 Scala 语法
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条