Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

initialization - In Scala, what exactly does 'val a: A = _' (underscore) mean?

What exactly does val a: A = _ initialize a value to? Is this a typed null? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

val a: A = _ is a compile error. For example:

scala> val a: String = _
<console>:1: error: unbound placeholder parameter
       val a: String = _
                       ^

What does work is var a: A = _ (note var instead of val). As Chuck says in his answer, this initialises the variable to a default value. From the Scala Language Specification:

0 if T is Int or one of its subrange types,
0L if T is Long,
0.0f if T is Float,
0.0d if T is Double,
false if T is Boolean,
() if T is Unit,
null for all other types T.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...