Skip to content

Commit 93408e8

Browse files
authored
Fix #24571: Handling nullable types in convertTo for adapting number constants to target number types (#24580)
Fix #24571 Handling nullable types in convertTo for adapting number constants to target number types
2 parents 9c55ded + 5a38283 commit 93408e8

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

compiler/src/dotty/tools/dotc/core/Constants.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package dotc
33
package core
44

55
import Types.*, Symbols.*, Contexts.*
6+
import NullOpsDecorator.stripNull
67
import printing.Printer
78
import printing.Texts.Text
89

@@ -149,7 +150,7 @@ object Constants {
149150
/** Convert constant value to conform to given type.
150151
*/
151152
def convertTo(pt: Type)(using Context): Constant | Null = {
152-
def classBound(pt: Type): Type = pt.dealias.stripTypeVar match {
153+
def classBound(pt: Type): Type = pt.dealias.stripTypeVar.stripNull() match {
153154
case tref: TypeRef if !tref.symbol.isClass && tref.info.exists =>
154155
classBound(tref.info.bounds.lo)
155156
case param: TypeParamRef =>

tests/pos/i24571.scala

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
val n: Byte = 2
2+
val n2: Byte | Null = 2
3+
val n3: Int = 2
4+
val n4: Int | Null = 2222
5+
val n5: Int | Byte = 2
6+
val n6: Byte | Int = 10000
7+
8+
val x: Option[Byte] = Option(2)
9+
val x2: Option[Byte] = Option[Byte](2)
10+
val x3: Option[Int] = Option(2)
11+
val x4: Option[Null] = Option(null)
12+
val x5: Option[Byte | Null] = Option(2)
13+
14+
trait MyOption[+T]
15+
16+
object MyOption:
17+
def apply[T](x: T | Null): MyOption[T] = ???
18+
def applyOld[T](x: T): MyOption[T] = ???
19+
20+
val test1: MyOption[Byte] = MyOption(2)
21+
val test2: MyOption[Byte] = MyOption.applyOld(2)
22+
val test3: MyOption[Int] = MyOption(2)
23+
val test4: MyOption[Null] = MyOption(null)
24+
val test5: MyOption[Byte | Null] = MyOption(2)

0 commit comments

Comments
 (0)