[trend_fp] RE: [trend_fp] class and object的反組譯結果

  • From: "shannon_chuang@xxxxxxxxxxxx" <shannon_chuang@xxxxxxxxxxxx>
  • To: "trend_fp@xxxxxxxxxxxxx" <trend_fp@xxxxxxxxxxxxx>
  • Date: Fri, 15 May 2015 06:01:08 +0000

http://stackoverflow.com/questions/609744/what-is-the-rationale-behind-having-companion-objects-in-scala
這URL提到一件有趣的事:雖然Companion是用來存static的資訊,但是它本身實作並不是用Java static做到的。

還有另外一個重要的問題:為什麼要用Companion object?
目的是讓class的本名可以當factory用,才不會一堆AbcFactory到處亂噴……

-Shannon

From: trend_fp-bounce@xxxxxxxxxxxxx [mailto:trend_fp-bounce@xxxxxxxxxxxxx] On
Behalf Of ???
Sent: Friday, May 15, 2015 12:50 PM
To: trend_fp@xxxxxxxxxxxxx
Subject: [trend_fp] class and object的反組譯結果

Account.scala
class Account
{
var class_id = "1234567"
def print_account() = { println(Account.object_id)}
}

object Account
{
//def print_account() = { println(Account.class_id)} cannot access class
Account' s class_ud
var object_id = "7654321"
}

編譯之後生出兩個class

Account.class
import scala.Predef$;

public class Account
{

public static void object_id_$eq(String s)
{
Account$.MODULE$.object_id_$eq(s);
}

public static String object_id()
{
return Account$.MODULE$.object_id();
}

public String class_id()
{
return class_id;
}

public void class_id_$eq(String x$1)
{
class_id = x$1;
}

public void print_account()
{
Predef$.MODULE$.println(Account$.MODULE$.object_id());
}
public Account()
{
class_id = "1234567";
}

private String class_id;
}

Account$.class -> object Account
public final class Account$
{

public String object_id()
{
return object_id;
}

public void object_id_$eq(String x$1)
{
object_id = x$1;
}

private Account$()
{
object_id = "7654321";
}

public static final Account$ MODULE$ = this;
private String object_id;

static
{
new Account$();
}
}

Mike

--
方鍾豪 (Mike Fang)
Pervasive Embedded Technology Lab
Department of Computer Science, National Chiao Tung University

<table class="TM_EMAIL_NOTICE"><tr><td><pre>
TREND MICRO EMAIL NOTICE
The information contained in this email and any attachments is confidential
and may be subject to copyright or other intellectual property protection.
If you are not the intended recipient, you are not authorized to use or
disclose this information, and we request that you notify us by reply mail or
telephone and delete the original message from your mail system.
</pre></td></tr></table>

Other related posts:

  • » [trend_fp] RE: [trend_fp] class and object的反組譯結果 - shannon_chuang@xxxxxxxxxxxx