çªç¶ã ããã®Scala 3ã®ã³ã¼ãã¯ã³ã³ãã¤ã«ããã ããããå ã«æ£è§£ãè¨ã£ã¦ããã¨ãã³ã³ãã¤ã«ããã(Scala 3.5.0)ã
class Foo: val x = y val y = 42
ã§ã¯ããã®Foo
ã«åãã¦ä»¥ä¸ã®å¼ã³åºããè¡ãã¨ã©ããªãã ããï¼
Foo().x
é©ããªããããã®å¼ã¯0
ã«è©ä¾¡ãããã
ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼ï¼
ãã³ãï¼
Scalaã®ã¯ã©ã¹ã«ãããã³ã³ã¹ãã©ã¯ã¿
Scalaã§ã¯ãclass
ãobject
ã®ä¸ã«ãããªãå°ã§æ¸ãããã³ã¼ãã¯ã³ã³ã¹ãã©ã¯ã¿ã¨ãã¦ããå®è¡ãã¦ããããã
class Foo(x: Int, y: Int): private val computed = x + y val field = computed Foo(1, 2).field // => 3
ããã«ãããä»ã®è¨èªã®ããã«constructor
ã¨ãã£ãååã®ã¡ã½ãããç¹å¥ã«ç¨æããå¿
è¦ããªãã
ãã®ã¾ã¾val
ã§ãã£ã¼ã«ããå®ç¾©ãã¦ãããã¨ã«ããããã£ã¼ã«ããåæåãããã«null
ã§åã¾ã£ã¦ããå®ã¶ããããªç¶æ
ãææ³ä¸åé¿ã§ããããã«ãªã£ã¦ããã
TypeScriptã§ã¯ãã³ã³ãã¤ã©ããã£ã¼ã«ãã®æªåæåãæ¤åºã§ãã:
class Foo { x: number y: number constructor () { this.x = 42 // Property 'y' has no initializer and is not definitely assigned in the constructor. } }
対ãã¦Scalaã¯ããã®å ´ã§ãå®ç¾©ã¨åæåãè¡ãããããã£ã¼ã«ããåæåããã¦ããªãã¨ãããã¨ã¯ãªã(ã³ã³ãã¤ã©ãæ¤åºãã):
class Foo { val x: Int = 42 val y: Int // åæåãã¦ããªãã®ãä¸ç®çç¶ } // => class Foo needs to be abstract, since val y: Int in class Foo is not defined
åæåé åº
åè¿°ã®ä»æ§ã«ãããèªæãªãã¨ã«ããã£ã¼ã«ãã¯å®ç¾©ããé ã«åæåããªããã°ãªããªã(å®ç¾©ããå ´æã§åæåããã®ã ãããããªã)ã
ãããåæåãã¦ããªããã£ã¼ã«ããå¾æ¹åç §ãã¦ãã¾ããããªã³ã¼ãã¯ã³ã³ãã¤ã«ãã¦ãã¾ã:
class Foo: val x = y // ãã®æç¹ã§yã®å¤ã¯ä¸æã ããã³ã³ãã¤ã«ãéã£ã¦0ã«ãªã£ã¦ãã¾ã val y = 42
ãã®ãã¨ãScalaããããã©ã³ãã§ããã¨ãããid:tanishiking24 ã«æãã¦ããã£ã:
å é¨çã«ã¯ã¾ãåãã£ã¼ã«ãã0å¤ã§åæåããã¤ã³ã¹ã¿ã³ã¹ãçæãã¦ããã®ãã¨ã³ã³ã¹ãã©ã¯ã¿ã§åãã£ã¼ã«ããx=yãy=42ã¿ãããªä»£å ¥ãçºçããã®ã§ãããªãã
Scalaã¯JVMè¨èªãªã®ã§ã³ã³ãã¤ã«ãããå¾ã®ã³ã¼ãã®é½åã§ãããªã£ã¦ãã¾ãããã ãèªåã¯ãããå¹´ã«1度ãããè¸ãã§ããæ°ãããã»ã»ã»ã
lazy val
ã«ããåé¿
å½ããåã ãããé åºã«æ°ãã¤ãããã¨ããã®ãç«æ´¾ãªåé¿çã ãScalaã§ã¯åºæ¬çã«ãå°ããè¦ç´ ããé ã«ããã£ã¼ã«ããæ¸ãã¦ããã®ãè¯ãããã
ãããé åºãæ··ã¿åã£ã¦ãããããå ´åã¯lazy val
ã«ãããã¨ã§ããã®åé¡ãåé¿ã§ããããã£ã¼ã«ããåãã¦å¼ã°ããã¿ã¤ãã³ã°ã§ä¸èº«ãè©ä¾¡ãããã®å¾ã¯ãã®å¤ã使ãããããã«ãªãã
class Foo { lazy val x = y val y = 42 } Foo().x // => 42
Safe Initialization
ã¨ããã§ãScala 3ã§ã¯Safe Initializationæ©è½ãã³ã³ãã¤ã©ãªãã·ã§ã³ã¨ãã¦è¿½å ããããããã¯ãã£ã¼ã«ãã®å¼ã³åºãé ã追跡ãã¦ãåæåãã¦ããªããã£ã¼ã«ãã®å¼ã³åºããæ¤ç¥ãã¦è¦åããæ©è½ã ã
ãã®ãªãã·ã§ã³ã¯-Wsafe-init
ãscalacOptions
ã«ä»ãããã¨ã§å©ç¨ã§ãã:
// build.sbt lazy val root = project .in(file(".")) .settings( // ... scalacOptions ++= Seq("-Wsafe-init"), )
ãã®æ©è½ã¯ç¶æ¿é¢ä¿ãæã¾ã£ã¦ãã¦ãæ£å¸¸ã«åä½ããããã ã
ã¾ã¨ã
- Scalaã§ã¯ãã¯ã©ã¹ãã£ã¼ã«ãã¯æ¸ããã¿ã¤ãã³ã°ã§åæåãã
- Scalaã³ã³ãã¤ã©ã¯ããããã£ã¼ã«ããåæåããã¿ã¤ãã³ã°ã§å¥ã®ãã£ã¼ã«ããåæåããã¦ããããæ¤ç¥ã§ããªã
- Safe Initializationã¯ã³ã³ãã¤ã©ã®æ©è½ãå¼·åãããã£ã¼ã«ãã®å¼ã³åºãã¿ã¤ãã³ã°ã追跡ãã¦å±éºãªå¼ã³åºããå¯ç¥ã§ãã