显示标签为“Scala”的博文。显示所有博文
显示标签为“Scala”的博文。显示所有博文

2017年2月28日星期二

scala convert int to long

参考http://stackoverflow.com/questions/19647525/how-to-convert-any-a-number-to-a-long

val number:AnyVal = 10
val l:Long = number.asInstanceOf[Number].longValue

直接用asInstanceOf[Long]会报错。

2016年1月27日星期三

Scala格式化数字输出

".3f".format(1.23456)  // 1.234

import java.text.DecimalFormat
val formatter = new DecimalFormat("#.###")
formatter.format(1)  // 1
formatter.format(1.34)  // 1.34
formatter.format(4.toFloat / 3)  // 1.333

2015年12月17日星期四

IntelliJ IDEA分别搭建基于maven和sbt的Scala项目

About the settings and keyboard shortcuts in IntelliJ, please see this doc.

About how to build Spark apps in IntelliJ, please see this doc.

2015年12月16日星期三

Scala中this.type的使用

一直有一个疑问没搞懂,有必要在这里发上一帖,参见我提的问题和回答:链接。

问题如下:
I defined two classes:
class A { def method1 = this }
class B extends A { def method2 = this }

val b = new B
Then I checked the type of b.method1:
scala> b.method1.getClass
res29: Class[_ <: A] = class B
In this case, I cannot use b.method1.method2:
scala> b.method1.method2
<console>:11: error: value method2 is not a member of A
              b.method1.method2
So I have to define A and B like this:
class A { def method1: this.type = this } 
class B extends A { def method2: this.type = this } 

val b = new B
Now I check the type of b.method1:
scala> b.method1.getClass
res31: Class[_ <: B] = class B
Here b.method1.method2 works:
scala> b.method1.method2
res32: b.type = B@4ff3ac
My question here is what does it mean by saying Class[_ <: A] = class B and Class[_ <: B] = class B? And why does the first doesn't work as Class[_ <: A] = class B seems to say that it's also class B?

Reactormonk很好地解答了我的疑问:
Let's split the expression Class[_ <: A] = class B. The first part, Class[_ <: A] tells you what the compiler knows at compile time, that b.method1 returns something of type Class[_ <: A]. The second part, class B mentions that you have a class B as value, but the compiler doesn't know that. That's runtime information.
this.type specializes the method for subclasses, where the type inferred from a plain thisdoesn't.

2015年12月7日星期一

Scala

Here are my own slides of learning Scala: link1 (Chinese), link2 (English).

This link is a Chinese tutorial of Scala.

See "A Tour of Scala" for more information.

Here are two video tutorials of Scala: link1, link2.